2017-07-07 1 views
-1
に複数のオブジェクトに

を内側のネストされたオブジェクトを拡張する方法を、私は配列にネストされたオブジェクトを拡張するために変換したい、follwingなどの詳細:のNode.jsで

{ 
"topic":"myTopic", 
"content":{ 
    "name": { 
     "tom1" : { 
      "value": "String", 
     }, 
     "tom2" : { 
      "value": "String", 
     }, 
     "tom3" : { 
      "value": "String", 
     } 
    } 
} 
} 

変換を、以下の形式に

を拡張

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

このヘルプあなたはい:あなたのような何かを試すことができ

[{ 
"topic":"myTopic", 
"content":{ 
    "name": { 
     "tom1" : { 
      "value": "String", 
     } 
    } 
} 
}, 

{ 
"topic":"myTopic", 
"content":{ 
    "name": {   
     "tom2" : { 
      "value": "String", 
     } 
    } 
} 
}, 
{ 
"topic":"myTopic", 
"content":{ 
    "name": {   
     "tom3" : { 
      "value": "String", 
     } 
    } 
} 
}] 
+1

わかりました。あなたの質問は何ですか? –

+0

私はオブジェクトの内部に複数の名前を持っていますが、新しい配列を拡張して新しい配列を生成する良い方法はありますか?それぞれが1つの名前を持っています – thomas

+0

なぜ 'topic'と' content'プロパティは同じオブジェクトにありますか?どのルールによって、オブジェクトを分割するかどうかを決定しますか? – trincot

答えて

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

あなたはmapObjectメソッドの一部を使用することができます:

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