我正在尝试在对象数组中获取特定对象。
var arr = [
{
id: "asd"
description: "V1",
output: [{type: "A", id:"ge"}]
},
{
id: "qwe"
description: "V2",
output: [{type: "B", id:"de"}]
}
];
console.log(arr.description);
和
console.log(arr.output.type);
所需的输出是:
{
{ description: "V1", output: {type: "A", id: "ge"}},
{ description: "V2", output: {type: "B", id: "de"}}
}
我还希望将对象的'output'
数组转换为对象,就像输出一样。怎么做到这一点?
在这里帮助我
答案 0 :(得分:0)
您希望的output
以无效的JSON语法开头......
假设output
只包含长度为1的数组。您可以这样做:
for (var i = 0; i < arr.length; i++) {
arr[i]['output'] = arr[i]['output'][0];
}
这将删除原始数组符号。
答案 1 :(得分:0)
要获取删除外部数组的所有项,可以执行以下操作:
var arr = [
{
id: "asd",
description: "V1",
output: [{type: "A", id:"ge"}]
},
{
id: "qwe",
description: "V2",
output: [{type: "B", id:"de"}]
}
];
for (let item of arr) {
console.log(item);
}
&#13;
答案 2 :(得分:0)
首先遍历数组,然后是output
值中的数组。请注意,我选择使用spread syntax从原始output
对象进行复制以避免变异:
var arr = [{
id: "asd",
description: "V1",
output: [{
type: "A",
id: "ge"
}]
},
{
id: "qwe",
description: "V2",
output: [{
type: "B",
id: "de"
}]
}
];
const objArr = [];
arr.forEach(obj => {
obj['output'].forEach(obj => {
objArr.push({ ...obj });
});
});
console.log(objArr);
&#13;
答案 3 :(得分:0)
首先你的数组语法有一个小错误。 它最多的是:
var arr = [
{
id: "asd",
description: "V1",
output: [{type: "A", id:"ge"}]
},
{
id: "qwe",
description: "V2",
output: [{type: "B", id:"de"}]
}
];
如果你只是想记录它,你可以使用它:
arr.forEach(function(item){console.log(item.description)})
此代码:
对于arr
数组中的每个对象,执行:
将该对象的名称设置为item
最后在description
item
您可以以其他形式使用此代码
祝你好运