2017-07-07 116 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; }