skip to Main Content

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:

[{},{}]

2

Answers


  1. 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);
    Login or Signup to reply.
  2. You dont have to create separate array and convert to string and then again push. Just do like this when value is string

    csvContent = [{
    "a": 123,
    "b": "ccc"
    },
    {
    "a": "bbb",
    "b": "aaa"
    }]
    
    for(let i in csvContent){
      console.log(typeof(csvContent[i].a))
     if(typeof(csvContent[i].a) != 'string'){
       csvContent[i].a = String( csvContent[i].a)
     }
    
    }
    
    console.log(csvContent)
    
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search