Home > Net >  Add new element to json array using Nodejs
Add new element to json array using Nodejs

Time:11-15

I have a json array [{id:1,data:"test1"},{id:2,data:"test2"}] I need to add a new element to each of the objects in the array based on the value of the "data" field. That is if the value of data is "test1", the new field data should be "test one type". The expected output is as below

[{id:1,data:"test1",type: "test1 Type"},{id:2,data:"test2",type: "test2 Type"}]

I tried with .push operation but it is adding new object to the array not updating the existing object. I am new to node NodeJs. Can you please help with this.

CodePudding user response:

u need to map add element via map function

const data = [{id:1, data:"test1"},{id:2,data:"test2"}];
data.map(element => {
    element.type = `${element.data} type`
    return element;
});

console.log(data)

CodePudding user response:

you can iterate over your array, and change each element with map and object destructuring:

let data = [{id:1,data:"test1"},{id:2,data:"test2"}];
let results = data.map(d => ({...d, type: `${d.data} Type`}));
console.log(results);

A more general form:

let data = [{id:1,data:"test1"},{id:2,data:"test2"}];

// you can set the type conditionally
let results1 = data.map(d => {
  let type
  if(d.data === 'test1') {
    type = 'some value'
  } else if(d.data === 'test2') {
    type = 'some other value'
  } else {
    type = 'default value'
  }
  return {...d, type}
});
console.log(results1);

// or you can have a function that gives the type
function getType(data) {
  // this function can do whatever you want
  // for example you can perform some computations, or call an api, etc.
  return 'some value'
}

let results2 = data.map(d => ({...d, type: getType(d.data)}));
console.log(results2);

UPDATE

To answer your question in the comments (how to group the results based on type):

you can use reduce:

let data = [
  {id: 1, data: "test1"},
  {id: 2, data: "test2"},
  {id: 3, data: "test1"},
  {id: 4, data: "test2"}
];

let results = data.map(d => ({ ...d,
  type: `${d.data} Type`
}));

let groupedDict = results.reduce((g, d) => ({ ...g,
  [d.type]: [...(g[d.type] || []), d]
}), {})

let groupedArray = Object.values(groupedDict)

console.log(groupedDict)
console.log(groupedArray)

Although this is a simplified example and I assumed the data is in correct form, i.e. all items have a type, and all types are correct, and not empty. In real situations, you should add some guards (type check, null check, etc.) to ensure your code does not crash and handle bad data as expected.

  • Related