将分开处理的对象合并成一个包含多个对象的数组。

huangapple go评论60阅读模式
英文:

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

问题

将分开的对象重新转换成初始格式的方法是:

let originalFormat = [];
for (let i in csvContent) {
  let obj = {
    "a": csvContent[i].a,
    "b": csvContent[i].b
  };
  originalFormat.push(obj);
}
console.log(originalFormat);

这将把分开的对象重新组合成初始的格式:[{},{},...]

英文:

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:

> [{},{}]

答案1

得分: 0

你可以尝试使用Array.prototype.map()方法。

> map()方法会在调用数组的每个元素上调用一个提供的函数,并创建一个新数组,其中包含调用结果。

演示:

<!-- 开始代码片段:js 隐藏:false 控制台:true Babel:false -->

<!-- 语言:lang-js -->

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

const res = csvContent.map(({ a, b }) => ({ a: a.toString(), b: b }));

console.log(res);

<!-- 结束代码片段 -->

英文:

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:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const csvContent = [
  { &quot;a&quot;: 123, &quot;b&quot;: &quot;ccc&quot; },
  { &quot;a&quot;: &quot;bbb&quot;, &quot;b&quot;: &quot;aaa&quot; }
];

const res = csvContent.map(({ a, b }) =&gt; ({ a: a.toString(), b: b }));

console.log(res);

<!-- end snippet -->

答案2

得分: 0

您不必创建单独的数组,然后将其转换为字符串,然后再次推送。只需在值为字符串时执行以下操作:

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)

这是您提供的代码的翻译部分。

英文:

You dont have to create separate array and convert to string and then again push. Just do like this when value is string

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

for(let i in csvContent){
  console.log(typeof(csvContent[i].a))
 if(typeof(csvContent[i].a) != &#39;string&#39;){
   csvContent[i].a = String( csvContent[i].a)
 }

}

console.log(csvContent)

huangapple
  • 本文由 发表于 2023年5月10日 17:37:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/76216919.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定