Home > Software design >  Arrays of objects
Arrays of objects

Time:10-03

Im a beginner in javascript and I have a trouble understanding why the console log doesnt returning me : { name: "Jim", Hungry: false }, { name: "Nick", Hungry: false }.

The exercise consist in returning an array of object and adding element to each object.

The console log only returns {name: "Jim"}, and doesn't iterate and i have trouble understanding what im doing wrong.

So here's my code :

const insert = (arr, obj) => {
  for (let i = 0; i <= arr.length; i  ) {
    return arr[i];
  }
  return arr;
};

console.log(
  insert([{ name: "Jim" }, { name: "Nick" }], {"Hungry": false})
);

CodePudding user response:

let items = []
const insert = (arr, obj) => {
  for (let i = 0; i < arr.length; i  ) {
     items.push(Object.assign(arr[i], obj));
  }
  return items
  
};

console.log(
  insert([{ name: "Jim" }, { name: "Nick" }], {"Hungry": false})
);

CodePudding user response:

const arr = [{ name: "Jim" }, { name: "Nick" }];
const obj = { Hungry: false };
const hunger = obj.Hungry;

console.log("The key of that object is " "  " Object.keys(obj)[0])
const ew = arr.map((item) => {
  item[Object.keys(obj)[0]] = hunger;
  return item
});

console.log("The updated array" JSON.stringify(ew));

This is a static solution for this question. If the number of keys in that object increases, this will not work.

CodePudding user response:

As mentioned above, returning within a for loop exits the loop and the outer context (your function), returning only the value following return.

What you want to do is map the array to a new one with each item merged with obj. This is particularly easy with spread syntax.

For example

const insert = (arr, obj) => arr.map((item) => ({ ...item, ...obj }))

console.log(
  insert([{ name: "Jim" }, { name: "Nick" }], {"Hungry": false})
);

  • Related