Iterate through Nested JavaScript Objects
You can create a recursive function like this to do a depth-first traversal of the cars
object.
var findObjectByLabel = function(obj, label) {
if(obj.label === label) { return obj; }
for(var i in obj) {
if(obj.hasOwnProperty(i)){
var foundLabel = findObjectByLabel(obj[i], label);
if(foundLabel) { return foundLabel; }
}
}
return null;
};
which can be called like so
findObjectByLabel(car, "Chevrolet");
loop through nested object javascript
You can use Object.entries
to get keys and values at once (as array of arrays [key, value]
):
const preference = {
"ethnicity": {
"value": "Gurung",
"rank": 1
},
"occupation": {
"value": "Banker",
"rank": 2
}
}
const preferenceRank = {}
for (const [key, { rank }] of Object.entries(preference)) {
preferenceRank[rank] = key
}
console.log(preferenceRank)
loop through nested object and change property
You can just loop over the value of mydata.language
with the help of forEach
and make show
as false
as:
Object.values(mydata.language).forEach((o) => o.show = false);
const mydata = {
message: 'Hello Vues!',
language: {
en: { show: false, displayname: 'English' },
ja: { show: true, displayname: 'Japanese' },
zh: { show: false, displayname: 'Chinese' },
},
};
Object.values(mydata.language).forEach((o) => o.show = false);
console.log(mydata);
/* This is not a part of answer. It is just to give the output full height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }
Looping through nested array of objects
This should do it:
const impacts = data.violations.map(({impact,nodes}) =>
[{impact}, ...nodes.map(({any,all,none}) => [...any, ...all, ...none]).flat()]
)
.flat();
const data = {
"violations": [{
"impact": "serious",
"nodes": [{
"any": [{
"impact": "critical"
},
{
"impact": "serious"
}
],
"all": [{
"impact": "moderate"
}],
"none": [{
"impact": "minor"
}]
}]
},
{
"impact": "serious",
"nodes": [{
"any": [{
"impact": "serious"
},
{
"impact": "minor"
}
],
"all": [{
"impact": "moderate"
}],
"none": [{
"impact": "serious"
}]
}]
},
{
"impact": "serious",
"nodes": [{
"any": [{
"impact": "critical"
},
{
"impact": "critical"
}
],
"all": [{
"impact": "moderate"
}],
"none": [{
"impact": "moderate"
}]
},
{
"any": [{
"impact": "critical"
},
{
"impact": "critical"
}
],
"all": [{
"impact": "moderate"
}],
"none": [{
"impact": "moderate"
}]
}
]
}
]
};
const impacts = data.violations.map(({impact,nodes}) =>
[{impact}, ...nodes.map(({any,all,none}) => [...any, ...all, ...none]).flat()]
)
.flat();
console.log( impacts );
Iterate through nested arrays of objects with an undetermined number of children node levels
We can recursively search all nodes until we find the match:
getItemRow(id){
return findNodeWithId(id, this.parents)
}
findNodeWithId(id, rootArr) {
for (let el of rootArr) {
if (el.id === id) {
return el
}
if (el.children) {
const idFoundInChildren = findNodeWithId(id, el.children)
if (idFoundInChildren !== null) {
return idFoundInChildren
}
}
}
return null
}
JavaScript iterate through nested objects for keys with values above given number
Here is an example using reduce()
, iterating the items
array of each category using forEach()
and pushing a template literal of matching elements to at the accumulator.
const foodmenu = { title: 'Menu', sections: [{ title: 'App', items: [{ title: 'Cookie', available: true, price: 3 }, { title: 'Snicker', available: true, price: 12 }, { title: 'Donuts', available: true, price: 11 }] }, { title: 'FullMeal', items: [{ title: 'Steak', available: false, price: 33 }, { title: 'Chinese Chicken', available: true, price: 14 }, { title: 'Fried Chicken', available: false, price: 17 }] },] };
function findPriceAbove(price, foodmenu) {
return foodmenu.reduce((a, category) => {
category.items.forEach(item => {
if (item.price > price && item.available) {
a.push(`${category.title}-${item.title}(${item.price})`);
}
})
return a;
}, []); // <-- pass an empty array as the initial accumulator value
}
console.log(findPriceAbove(13, foodmenu.sections))
How to iterate through nested Objects and combine key and value?
I modified what you did a bit, you can you flatMap
const products = {
value: {
phone: [],
lamp: [],
car: ["bmw", "toyota", "audi"]
}
};
const mappedProducts = Object.entries(products.value).flatMap(([value, items]) => {
//console.log("value :", value, "items :", items)
if (items.length > 0) {
return items.map(item => `${value}-${item}`);
} else {
return [value];
}
});
console.log(mappedProducts);
Related Topics
Regex to Match All Instances Not Inside Quotes
Why Can't I Add Properties to a String Object in JavaScript
Determine Original Size of Image Cross Browser
Detect Back Button Click in Browser
How to Convert HTML to JSON Using PHP
Drop-Down Box Dependent on the Option Selected in Another Drop-Down Box
How to Export HTML Table to Excel Using JavaScript
How to Auto-Scroll to End of Div When Data Is Added
React: Script Tag Not Working When Inserted Using Dangerouslysetinnerhtml
How to Create Checkbox Inside Dropdown
What Does the "|" (Single Pipe) Do in JavaScript
Url Hash-Bang (#!/) Prefix Instead of Simple Hash (#/) in Angular 1.6
In JavaScript, Why Is the "This" Operator Inconsistent
Can JavaScript Connect with MySQL
How to Access Shadow Dom Elements Through the Parent Document
Trigger Standard HTML5 Validation (Form) Without Using Submit Button