Skip to content
Advertisement

How to add “new” element/objects s to a list in javascript?

Let’s say I have a List of objects in javascript.

demoList = [
 {
  name: "first object",
  value: "first value",
  year: "first year"
 },
 {
  name: "second object",
  value: "second value",
  year: "second year"
 },
 {
  name: "third object",
  value: "third value",
  year: "third year"
 },
 {
  name: "fourth object",
  value: "fourth value",
  year: "fourth year"
 },
]

Now I make some API call and get more data like …

moreData = [
 {
  name: "first object",
  value: "first value",
  year: "first year"
 },
 {
  name: "sixth object",
  value: "sixth value",
  year: "sixth year"
 },
 {
  name: "seventh object",
  value: "seventh value",
  year: "seventh year"
 },
]

I want to add the new objects i.e the sixth and seventh to my existing demoList and discard the existing object i.e. first object. How do I achieve this in javascript with less time complexity? No I cannot use sets. Also let’s just say the criteria for comparison is the name. Other values can be same.

Advertisement

Answer

We can check the result by Array.prototype.find() method and then push it.

const demoList = [{
    name: "first object",
    value: "first value",
    year: "first year"
  },
  {
    name: "second object",
    value: "second value",
    year: "second year"
  },
  {
    name: "third object",
    value: "third value",
    year: "third year"
  },
  {
    name: "fourth object",
    value: "fourth value",
    year: "fourth year"
  },
];

const moreData = [{
    name: "first object",
    value: "first value",
    year: "first year"
  },
  {
    name: "sixth object",
    value: "sixth value",
    year: "sixth year"
  },
  {
    name: "seventh object",
    value: "seventh value",
    year: "seventh year"
  },
]

const mergeObjectsByName = (org, more) => {
  const res = [...org];
  for (let m of more) {
    if (res.find(it => it.name === m.name)) continue;
    res.push(m)
  }
  return res;
}
console.log(mergeObjectsByName(demoList, moreData));
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement