在Node.js中,我想转换为将嵌套对象扩展为数组,详情如下:
{
"topic":"myTopic",
"content":{
"name": {
"tom1" : {
"value": "String",
},
"tom2" : {
"value": "String",
},
"tom3" : {
"value": "String",
}
}
}
}
转换并扩展为以下格式
[{
"topic":"myTopic",
"content":{
"name": {
"tom1" : {
"value": "String",
}
}
}
},
{
"topic":"myTopic",
"content":{
"name": {
"tom2" : {
"value": "String",
}
}
}
},
{
"topic":"myTopic",
"content":{
"name": {
"tom3" : {
"value": "String",
}
}
}
}]
答案 0 :(得分:0)
您可以尝试以下内容:
var result = []; // contains the array you're looking for
var test = { "topic":"myTopic", "content":{ "name": { "tom1" : { "value": "String", }, "tom2" : { "value": "String", }, "tom3" : { "value": "String", } } } };
Object.keys(test.content.name).map((e,i) => {
let temp = {};
temp[e] = test.content.name[e];
result.push({topic: test.topic, content: { name: temp }});
});
这对你有帮助吗?
答案 1 :(得分:0)
x = { "topic":"myTopic", "content":{ "name": { "tom1" : { "value": "String", }, "tom2" : { "value": "String", }, "tom3" : { "value": "String", } } } };
console.log(Object.keys(x.content.name).map((n) => {
let y = JSON.parse(JSON.stringify(x));
y.content.name = {};
y.content.name[n] = x.content.name[n];
return y;
}))

答案 2 :(得分:0)
您可以使用map
和一些Object
方法:
function splitObject(obj) {
return Object.keys(obj.content.name).map( key => Object.assign({}, {
content: { name: { [key]: obj.content.name[key] } }
}) );
}
const obj = {
topic: "myTopic",
content: {
name: {
tom1: {
value: "String",
},
tom2: {
value: "String",
},
tom3: {
value: "String",
}
}
}
};
const result = splitObject(obj);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }