英文:
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 = [
{ "a": 123, "b": "ccc" },
{ "a": "bbb", "b": "aaa" }
];
const res = csvContent.map(({ a, b }) => ({ 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 = [{
"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)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论