2017-07-07 57 views
-1

在Node.js的,我要转换为嵌套对象延伸到一个数组,细节follwing:如何内部嵌套对象扩展为多个对象

{ 
"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", 
     } 
    } 
} 
}] 
+1

好。你有什么问题? –

+0

我有多个名称内的对象,是否有一种很好的方式来扩展并生成一个新的数组,在这个新的数组中,每个名称都有一个名称 – thomas

+0

为什么'topic'和'content'属性仍然在同一个对象中?你确定哪个规则应该被拆分或不拆分? – trincot

回答

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 }}); 
}); 

这是否帮助你吗?

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; 
 
}))

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; }