Search code examples
javascriptarraysloopsobjectoop

How do I make separated processed objects into single array with multiple object


I have an array of objects:

csvContent = [{
  "a": 123,
  "b": "ccc"
},
{
  "a": "bbb",
  "b": "aaa"
}];

I process first "a" key value to a string use

for (let i in csvContent){
  dataString.a = String(csvContent[i].a);
  console.log(dataString.a);
}

But the result from the loop is:

result on first loop is

{
"a": "123",
"b": "ccc"
}

result on second loop is

{
  "a": "bbb",
  "b": "aaa"
}

How to make those separated object back to the beginning format:

[{},{}]


Solution

  • You can try using Array.prototype.map()

    The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

    Demo:

    const csvContent = [
      { "a": 123, "b": "ccc" },
      { "a": "bbb", "b": "aaa" }
    ];
    
    const res = csvContent.map(({ a, b }) => ({ a: a.toString(), b: b }));
    
    console.log(res);