How to loop through object of objects and add new key-value data using Javascript?
Consider you have an array of summer fruits as below:
You need to add new key/value
Solution
You can use JavaScripts'
let summerFruits = ['apples', 'bananas', 'mangoes'];and object of objects as below:
let obj = { 0: { name: 'apples' }, 1: { name: 'bananas' }, 2: { name: 'apples' }, 3: { name: 'oranges' } }Problem:
You need to add new key/value
season: 'summer'
to existing object, if it exists summer fruits only.
Solution
You can use JavaScripts'
Object.keys
to loop through object of objects and findIndex
to find the key or index that matches your condition and update the object by an key.
let summerFruits = ['apples', 'bananas', 'mangoes']; let obj = { 0: { name: 'apples' }, 1: { name: 'bananas' }, 2: { name: 'mangoes' }, 3: { name: 'oranges' } }; Object.keys(obj).forEach(key => summerFruits.findIndex(fruit => fruit === obj[key].name) > -1 ? obj[key].season = 'summer' : '' ); console.log(obj); //Output /* {0: {…}, 1: {…}, 2: {…}, 3: {…}} 0: {name: "apples", season: "summer"} 1: {name: "bananas", season: "summer"} 2: {name: "mangoes", season: "summer"} 3: {name: "oranges"} */
Comments
Post a Comment