[英]How to put multiple objects in one array in javascript?
How to put multiple objects in one array in javascript?如何在javascript中将多个对象放在一个数组中?
I have n json strings like this:我有n个这样的json字符串:
first object
'[{"name":"1","position":{"x":-28.890169060450745,"y":-89.45,"z":103.39384013230637},"property":{"floor":"Platform", "name":"1"}]'
second object
'[{"name":"2","position":{"x":-28.890169060450745,"y":-89.45,"z":103.39384013230637},"property":{"floor":"Platform", "name":"2"}]'
third object
'[{"name":"3","position":{"x":-28.890169060450745,"y":-89.45,"z":103.39384013230637},"property":{"floor":"Platform", "name":"3"}]'
...
nth object
Here I want to put n obejects into one result在这里,我想将 n 个对象放入一个结果中
like this像这样
'[{"name":"1","position":{"x":-28.890169060450745,"y":-89.45,"z":103.39384013230637},"property":{"floor":"승강장","name":"1"},
[{"name":"2","position":{"x":-28.890169060450745,"y":-89.45,"z":103.39384013230637},"property":{"floor":"승강장","name":"2"}],
[{"name":"3","position":{"x":-28.890169060450745,"y":-89.45,"z":103.39384013230637},"property":{"floor":"승강장","name":"3"}]'
For this, I tried the following, but if I push it, it comes into the Array itself.为此,我尝试了以下操作,但如果我推动它,它会进入数组本身。
for (let i = 0; i < DataList.length; i++) {
if (i == 0) {
mergetData = JSON.parse(DataList[0]);
continue;
} else {
mergetData.push(JSON.parse(DataList[i]));
}
}
I am wondering how can I solve this problem.我想知道如何解决这个问题。
Best Regards!此致!
Parse all the JSON arrays, then concatenate them into a single array.解析所有 JSON 数组,然后将它们连接成一个数组。
let parsedData = Datalist.map(s => JSON.parse(s));
let mergeData = [].concat(...parsedData);
Your are asking how to put multiple objects in one array but your desired output is the string object.您在问如何将多个对象放在一个数组中,但您想要的输出是字符串对象。 So I'm considering your desired output as the actual question :)所以我正在考虑您想要的输出作为实际问题:)
For that you just have to iterate through your DataList
and merge values into an string object.为此,您只需遍历您的DataList
并将值合并到一个字符串对象中。
StringObject = ''
for(let i=0; i < DataList.length; i++){
if(i===0)
StringObject += DataList[i]
else
StringObject += ',' + DataList[i]
}
console.log(StringObject)
Or just要不就
StringObject = String(DataList)
console.log(StringObject)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.