[using for loop to add prooperty]Add Key-Value Pairs to JavaScript Objects

Tell us what’s happening:

i solved the challenge manually by adding property and value then i tried using below code it only works partially. The output is {"apples":25,"oranges":32,"plums":28,"bananas":27,"grapes":27,"strawberries":27} all the newly added properties(bananas,grapes,strawb) has the same value

Your code so far


let foods = {
  apples: 25,
  oranges: 32,
  plums: 28
};

// change code below this line
let arr=['bananas','grapes','strawberries'];
let val=[13,35,27];
for(let i=0;i<arr.length;i++){
  for(let j=0;j<val.length;++j){foods[arr[i]]=val[j];}
}
/*foods.bananas=13;
  foods.grapes=35;
  foods.strawberries=27;*/
  //foods.bab
// change code above this line

console.log(JSON.stringify(foods));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-data-structures/add-key-value-pairs-to-javascript-objects

why do you have an inner loop ?

to add values to the property.

right but you can access the corresponding values with just your outer loop, since the values are in order and of the same length

Thank you using single loop fixed it. :smile: )

but what if we have to select values from a larger array?

It doesn’t matter as long as the property array order and length matches with value array order and length

1 Like

I understand thank you :slight_smile:

you don’t need the inner loop , because the first loop you have can give you the result you need ,
just inject this code
foods[arr[i]]=val[i];
every time i increments you can get new property name from arr and new property value from val .