unable to loop through nested array - javascript

I am trying to loop through the following array but did not succeed,
is my approach correct?
I have done many changes to my code it might be not as it was
my try :
var gender = ["men", "women"];
var category = [
"topwear",
"bottomwear",
"indianwear",
"westernwear",
];
for (var i = 0; i < categories.length; i++) {
for (var g = 0; g < gender.length; g++) {
for (j = 0; j < categories[i][gender[g]].length; j++) {
for (var c = 0; c < category.length; c++) {
console.log("=======category========", category[c]);
for (k = 0; k < categories[i][gender[g]][j][category[c]].length; k++) {
console.log(categories[i][gender[g]][j][category[c]][k]);
}
}
}
}
}
the array :
[
{
men: [
{
topwear: [
"men-topwear",
"men-tshirts",
"men-casual-shirts",
"men-formal-shirts",
"men-sweatshirts",
"men-sweaters",
"men-jackets",
"men-blazers",
"men-suits",
"rain-jacket",
],
},
{
bottomwear: [
"men-jeans",
"men-casual-trousers",
"men-formal-trousers",
"mens-shorts",
"men-trackpants",
"men-innerwear",
"men-briefs-and-trunks",
"men-boxers",
"men-innerwear-vests",
"men-nightwear",
"men-thermals",
],
},
],
},
{
women: [
{
indianwear: [
"women-kurtas-kurtis-suits",
"ethnic-tops",
"ethnic-wear-dresses-menu",
"women-ethnic-bottomwear?f=categories%3AChuridar%2CLeggings%2CSalwar",
"skirts-palazzos",
"saree",
"dress-material",
"lehenga-choli",
"dupatta-shawl",
"women-ethnic-wear-jackets",
"dresses?f=Gender%3Amen%20women%2Cwomen",
"jumpsuits?f=Gender%3Amen%20women%2Cwomen",
],
},
{
westernwear: [
"women-shirts-tops-tees",
"women-jeans-jeggings",
"women-trousers",
"women-shorts-skirts",
"women-shrugs",
"women-sweaters-sweatshirts",
"women-jackets-coats",
"women-blazers-waistcoats",
],
},
],
},
];
I need to get the names within the array.
coz i need to use it in the code which i am going to write inside the inner
most loop.
thanks in advance

Your code expects each object in the array to have both men and women properties. But these properties are in separate array elements. So you need to check whether the property exists before trying to loop over its elements. Otherwise you'll try to get the length of an undefined property.
Similarly, each object in the men or women array has just a single property, not all the properties in the category array.
Looping will be much easier if you assign variables to the current element of the array, so you don't need long expressions with lots of indexes like categories[i][gender[g]][j][category[c]][k]. And using forEach() will simplify this.
var gender = ["men", "women"];
var category = [
"topwear",
"bottomwear",
"indianwear",
"westernwear",
];
var categories = [{
men: [{
topwear: [
"men-topwear",
"men-tshirts",
"men-casual-shirts",
"men-formal-shirts",
"men-sweatshirts",
"men-sweaters",
"men-jackets",
"men-blazers",
"men-suits",
"rain-jacket",
],
},
{
bottomwear: [
"men-jeans",
"men-casual-trousers",
"men-formal-trousers",
"mens-shorts",
"men-trackpants",
"men-innerwear",
"men-briefs-and-trunks",
"men-boxers",
"men-innerwear-vests",
"men-nightwear",
"men-thermals",
],
},
],
},
{
women: [{
indianwear: [
"women-kurtas-kurtis-suits",
"ethnic-tops",
"ethnic-wear-dresses-menu",
"women-ethnic-bottomwear?f=categories%3AChuridar%2CLeggings%2CSalwar",
"skirts-palazzos",
"saree",
"dress-material",
"lehenga-choli",
"dupatta-shawl",
"women-ethnic-wear-jackets",
"dresses?f=Gender%3Amen%20women%2Cwomen",
"jumpsuits?f=Gender%3Amen%20women%2Cwomen",
],
},
{
westernwear: [
"women-shirts-tops-tees",
"women-jeans-jeggings",
"women-trousers",
"women-shorts-skirts",
"women-shrugs",
"women-sweaters-sweatshirts",
"women-jackets-coats",
"women-blazers-waistcoats",
],
},
],
},
];
categories.forEach(catItem =>
gender.forEach(genItem => {
if (catItem[genItem]) {
category.forEach(cat => {
console.log("=======category========", cat);
catItem[genItem].forEach(i => {
if (i[cat]) {
i[cat].forEach(x => console.log(x));
}
});
});
}
})
);

Related

how to get the value by the help of includes/index of

how to get the value in any way if key does match with "Item"
const data = [{
"Item-55566": "phone",
},
{
"Items-44555": "Case",
}
];
/* How to get value if index found by Item */
for(let i = 0; i<data.length; i++) {
console.log(data[i].includes("Item"));
//Expecting phone and case
}
for-in allows you to loop through the keys in an object. Not to be confused with for-of, which loop through elements in an array.
const data = [{
"Item-55566": "phone",
},
{
"Items-44555": "Case",
}
];
for(let datum of data)
{
for(let key in datum)
{
if(key.includes("Item"))
{
console.log(datum[key]);
}
}
}
In the simple way just change data[i].includes("Item") to data[i].keys().includes("Item").
BUT! Could we have some alternative data set here? For example:
const data = [{
"Item-55566": "phone",
"SomeKey: "Some Value",
123123: "Numeric key with value"
},
{
"Items-44555": "Case",
"Another-key": "Another value"
}
];
In this case you need to put some changes in your code to find correct keys & values:
for(let i = 0; i<data.length; i++) {
data[i].keys().forEach(v=>{
String(v).includes("Item") && console.log("Got index: ${i}, key: ${v}, value: ${data[i][v]}")
})
}
The for loop iterates through the two objects, so you can check to see whether the object has that particular property using hasOwnProperty()
const data = [
{
"Item-55566": "phone",
},
{
"Items-44555": "Case",
},
];
/* How to get value if index found by Item */
for (let i = 0; i < data.length; i++) {
if (data[i].hasOwnProperty("Item-55566")) {
console.log(data[i]);
}
}
If you want to keep your loop (good that it's only one loop compared to other answers) you can do it with Object.keys and values:
const data = [{
"Item-55566": "phone",
},
{
"Items-44555": "Case",
}
];
/* How to get value if index found by Item */
for(let i = 0; i<data.length; i++) {
if(Object.keys(data[i])[0].includes('Item')){
console.log(Object.values(data[i])[0]);
}
}
You can use .filter to filter all items of the data array which includes Item text.
Then you can use .map to render new value from each object comes from data array.
const data = [
{"Item-55566": "phone", },
{ "Items-44555": "Case",},
{ "Other-44555": "Nope",}];
var filteredItems = data.filter(item => Object.keys(item)[0].includes("Item"));
console.log(filteredItems.map(item => Object.values(item)[0]));
Refactor code - By using .reduce()
const data = [
{"Item-55566": "phone", },
{ "Items-44555": "Case",},
{ "Other-44555": "Nope",}];
var res = data.reduce((prev, curr) =>
{
var entries = Object.entries(curr)[0];
if(entries[0].includes("Item"))
prev.push(entries[1]);
return prev;
}, []);
console.log(res);

Ask for help on how to get all the filtered list from specific array

I have an object in an array called "Person".
Within the object "Person", there is an array called "info".
My goal is to get all the values with the prefix "age:" in an array "info" when filtering by "gender:male". So, my desired output will be 1 to 9 because I want also to remove duplicates.
Below is my code but the results are only two values (1 and 4). Maybe the output is one value per person.
I spent a lot of hours playing the code but no luck. That's why I bring my problem here hoping anybody who is an expert on this can help me.
<script>
var array = [
{
"person": {
"info": [
"age:1",
"age:2",
"age:3",
"age:4",
"age:5",
"age:6",
"gender:male"
]
},
"person": {
"info": [
"age:4",
"age:5",
"age:6",
"age:7",
"age:8",
"age:9",
"gender:male"
]
},
"person": {
"info": [
"age:8",
"age:9",
"age:10",
"age:11",
"age:12",
"age:13",
"gender:female"
]
}
}
]
var filteredAges = [];
for (i = 0; i < array.length; i++) {
var infoGroup = array[i].person.info,
ageGroup = [];
for (j = 0; j < infoGroup.length; j++) {
ageGroup.push(infoGroup[j]);
var ageInfo = ageGroup.find(ages => ages.includes('age:'));
};
if (ageInfo) {
if (filteredAges.indexOf(ageInfo) == -1) {
filteredAges.push(ageInfo)
}
}
}
for (i = 0;i < filteredAges.length; i++) {
console.log(filteredAges[i]);
}
</script>
Seems like all your object keys are just person i.e
[
{
person: {...},
person: {...},
person: {...}
}
]
So when the variable array is evaluated it just has one person
You need to restructure your data maybe like below or something similar
Example - 1
[
{ person: {...} },
{ person: {...} },
{ person: {...} },
]
Example - 2
[
[ { person: {...} } ],
[ { person: {...} } ],
[ { person: {...} } ]
]
After fixing this you can try debugging your problem
If you want to get all items in info array that has "age:"
you can use filter like this
const ageInfos = [
"age:8", "age:9",
"age:10", "age:11",
"age:12", "age:13",
"gender:female"
].filter(x => x.startsWith("age:"))
Your output - ageInfos will be
["age:8", "age:9", "age:10", "age:11", "age:12", "age:13"]
You can also use Set to only collect unique strings or just push everything to an array and later use Set to return only unique values like this
const arrayWithDuplicates = ['a', 1, 'a', 2, '1'];
const unique = [...new Set(arrayWithDuplicates)];
console.log(unique); // unique is ['a', 1, 2, '1']
First of all, your JSON is wrong. You just overright person object.
Data structure is really awful, I would recommend you to rethink it.
Assuming person will not be overwritten I came up with this solution.
var array = [
{
"person": {
"info": [
"age:1",
"age:2",
"age:3",
"age:4",
"age:5",
"age:6",
"gender:male"
]
},
"person1": {
"info": [
"age:4",
"age:5",
"age:6",
"age:7",
"age:8",
"age:9",
"gender:male"
]
},
"person2": {
"info": [
"age:8",
"age:9",
"age:10",
"age:11",
"age:12",
"age:13",
"gender:female"
]
}
}
]
let agesArray = []
let ages = []
array.forEach((peopleObj) => {
for (const index in peopleObj) {
ages = peopleObj[index].info.map((age) => {
const ageNumber = age.split(':')[1]
if (parseInt(ageNumber)) {
return ageNumber
}
}).filter(val => !!val)
agesArray = [...agesArray, ...ages]
}
})
Thanks a lot guys. I'll apply all of your ideas and try if it can solve my problem.

Object Array Formatting

I have an object in this format:
var request = {
"student": [
[
"name",
"age"
],
[
"Tom",
12
],
[
"Jack",
13
]
]
};
I want to transform it into this:
var request = {
"student": [
{
"name": "Tom",
"age": 12
},
{
"name": "Jack",
"age": 13
}
]
}
I tried doing it this way:
var response = [];
var keysCount = req.result[0].length;
var responseCount = req.result.length - 1;
var i = 0,
j = 0,
key;
for (j = 0; j < responseCount; j++) {
for (i = 0; i < keysCount; i++) {
key = req.result[0][i];
response[j][key] = req.result[j + 1][i];
}
}
return response;
But, it is not working as expected.
It's a matter of looping through the first array and creating an array of objects for all the remaining arrays, using values at matching indexes to create properties on object:
var request = {
"student": [
[
"name",
"age"
],
[
"Tom",
12
],
[
"Jack",
13
]
]
};
// Get the header array
var headers = request.student[0];
// Create the new array but mapping the other entries...
var newArray = request.student.slice(1).map(function(entry) {
// Create an object
var newEntry = {};
// Fill it in with the values at matching indexes
headers.forEach(function(name, index) {
newEntry[name] = entry[index];
});
// Return the new object
return newEntry;
});
console.log(newArray);
I would make a small function tabularize that takes an array of data where the first element is an array of headers, and the remaining elements are the rows
Code that follows uses ES6. If you need ES5 support, you can safely transpile this code using a tool like babel.
// your original data
var request = {
"student": [
[
"name",
"age"
],
[
"Tom",
12
],
[
"Jack",
13
]
]
};
// tabularize function
var tabularize = ([headers, ...rows])=>
rows.map(row=>
headers.reduce((acc,h,i)=>
Object.assign(acc, {[h]: row[i]}), {}));
// your transformed object
var request2 = {student: tabularize(request.student)};
// log the output
console.log(request2);
//=> {"student":[{"name":"Tom","age":12},{"name":"Jack","age":13}]}
Or you can create the request object with the intended shape by passing the tabular data directly into the tabularize function at the time of object creation
// tabularize function
var tabularize = ([headers, ...rows])=>
rows.map(row=>
headers.reduce((acc,h,i)=>
Object.assign(acc, {[h]: row[i]}), {}));
// your request object
var request = {
student: tabularize([
[
"name",
"age"
],
[
"Tom",
12
],
[
"Jack",
13
]
])
};
// log the output
console.log(request);
//=> {"student":[{"name":"Tom","age":12},{"name":"Jack","age":13}]}
Let's start off by writing a little function just to create an object from two arrays, one of keys and one of their values:
function makeObjectFromPairs(keys, values) {
var object = {};
for (var i = 0; i < keys.length; i++) {
object[keys[i]] = values[i];
}
return object;
}
// makeObjectFromPairs(['a', 'b'], [1, 2]) === {a: 1, b: 2}
Now we can use the first element of the students array as the keys, and each of the remaining elements as the values.
var keys = students[0];
var result = [];
for (var i = 1; i < students.length; i++) {
result.push(makeObjectFromPairs(keys, students[i]);
}
You could use Array#map etc. as an alternative for the loops, but perhaps this basic approach is more accessible.
Fixing your original code
Since you made a valiant effort to solve this yourself, let's review your code and see where you went wrong. The key point is that you are not initializing each element in your output to an empty object before starting to add key/value pairs to it.
for (j = 0; j < responseCount; j++) {
// Here, you need to initialize the response element to an empty object.
response[j] = {};
Another solution :
var request = {
"student": [
[
"name",
"age"
],
[
"Tom",
12
],
[
"Jack",
13
]
]
};
var response = {};
var students = [];
var responseCount = request.student.length - 1;
var j = 0,
key;
for (j = 0; j < responseCount; j++) {
var student = {};
request.student[0].forEach(function(name, index) {
student[name] = request.student[1 + j][index];
});
students.push(student)
}
response["students"] = students;
console.log(response); // {"students":[{"name":"Tom","age":12},{"name":"Jack","age":13}]}
Lodash solution
var keys = _.head(request.student);
var valueGroups = _.flatten(_.zip(_.tail(request.student)));
var studentObjects = valueGroups.map(function(values){
return values.reduce(function(obj, value, index){
obj[keys[index]] = value;
return obj;
}, {});
});
console.log(studentObjects);
https://jsfiddle.net/mjL9c7wt/
Simple Javascript solution :
var request = {
"student": [
[
"name",
"age"
],
[
"Tom",
12
],
[
"Jack",
13
]
]
};
var students = [];
for(var x = 1; x<request.student.length;x++)
{
var temp = { 'name' : request.student[x][0],
'age' : request.student[x][1]
}
students.push(temp);
}
request = { 'students' : students}
console.log(request);

JSON data transformation from table-like format to JSON?

I have data that's in this format:
{
"columns": [
{
"values": [
{
"data": [
"Project Name",
"Owner",
"Creation Date",
"Completed Tasks"
]
}
]
}
],
"rows": [
{
"values": [
{
"data": [
"My Project 1",
"Franklin",
"7/1/2015",
"387"
]
}
]
},
{
"values": [
{
"data": [
"My Project 2",
"Beth",
"7/12/2015",
"402"
]
}
]
}
]
}
Is there some super short/easy way I can format it like so:
{
"projects": [
{
"projectName": "My Project 1",
"owner": "Franklin",
"creationDate": "7/1/2015",
"completedTasks": "387"
},
{
"projectName": "My Project 2",
"owner": "Beth",
"creationDate": "7/12/2015",
"completedTasks": "402"
}
]
}
I've already got the column name translation code:
r = s.replace(/\%/g, 'Perc')
.replace(/^[0-9A-Z]/g, function (x) {
return x.toLowerCase();
}).replace(/[\(\)\s]/g, '');
Before I dive into this with a bunch of forEach loops, I was wondering if there was a super quick way to transform this. I'm open to using libraries such as Underscore.
function translate(str) {
return str.replace(/\%/g, 'Perc')
.replace(/^[0-9A-Z]/g, function (x) {
return x.toLowerCase();
})
.replace(/[\(\)\s]/g, '');
}
function newFormat(obj) {
// grab the column names
var colNames = obj.columns[0].values[0].data;
// create a new temporary array
var out = [];
var rows = obj.rows;
// loop over the rows
rows.forEach(function (row) {
var record = row.values[0].data;
// create a new object, loop over the existing array elements
// and add them to the object using the column names as keys
var newRec = {};
for (var i = 0, l = record.length; i < l; i++) {
newRec[translate(colNames[i])] = record[i];
}
// push the new object to the array
out.push(newRec);
});
// return the final object
return { projects: out };
}
DEMO
There is no easy way, and this is really not that complex of an operation, even using for loops. I don't know why you would want to use regex to do this.
I would start with reading out the column values into a numerically indexed array.
So something like:
var sourceData = JSON.parse(yourJSONstring);
var columns = sourceData.columns[0].values[0].data;
Now you have a convenient way to start building your desired object. You can use the columns array created above to provide property key labels in your final object.
var sourceRows = sourceData.rows;
var finalData = {
"projects": []
};
// iterate through rows and write to object
for (i = 0; i < sourceRows.length; i++) {
var sourceRow = sourceRows[i].values.data;
// load data from row in finalData object
for (j = 0; j < sourceRow.length; j++) {
finalData.projects[i][columns[j]] = sourceRow[j];
}
}
That should do the trick for you.

How can get all objects whose sub object's property matches my string array using linq.js?

I have an array of tag names:
var tags = ['tagOne', 'tagTwo']
Which I want to use, to query the array below and get all items which match a tag.
var items =
[
{
'name': 'itemOne',
'tags': [
{ name: 'tagOne' }
]
},
{
'name': 'itemTwo',
'tags': [
{ name: 'tagTwo' }
]
}
];
How can I do this with linq Js? I.E in this case both items would be returned
Try this; it may not be the most efficient way (I've never used linq.js before) but it will work:
// Enumerate through the items
var matches = Enumerable.From(items)
.Where(function(item) {
// Enumerate through the item's tags
return Enumerable.From(item.tags).Any(function(tag) {
// Find matching tags by name
return Enumerable.From(tags).Contains(tag.name);
})
})
.ToArray();
This should work for you:-
Items
var items =
[
{
'name': 'itemOne',
'tags': [
{ name: 'tagOne' }
]
},
{
'name': 'itemTwo',
'tags': [
{ name: 'tagTwo' }
]
},
{
'name': 'itemThree',
'tags': [
{ name: 'tagThree' }
]
}
];
Tags:-
var tags = ['tagOne', 'tagTwo'];
Search for Tags:-
var fillteredItems = items.filter(function(item){
var tagsInItem = item["tags"];
for (var i = 0; i < tags.length; i++) {
for (var j = 0; j < tagsInItem.length; j++) {
if(tags[i]==tagsInItem[j].name)
return item;
};
};
});
Print Results:-
fillteredItems.forEach(function(item){
console.log("items",item);
})

Categories