I'm trying to form an array consisting of an object whose value is, in turn, a group of key-value pair of objects from an array of objects. Basically, I'm trying to assign a group of objects in an array (from a Request JSON) as a value to an object key (parentKey) in another array. Kindly help me out with the following:
Source - Array of objects:
{
"Array": [
{
"key1": "value1",
"key2": "value2",
"key3": "value3"
},
{
"key1": "value1",
"key2": "value2",
"key3": "value3"
},
{
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
]
}
Result - Array with an object whose value is a group of key-value pair of objects:
{
"Array":[{
"parentKey": {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
},{
"parentKey": {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
},{
"parentKey": {
"key1": "value1",
"key2": "value2",
"key3": "value3"
}
}]
}
Just loop over the Array
property of the object and push the parentKey
object in a new array. And finally you can set that array to a new object with property Array
.
var input = { "Array":[{ "parentKey": { "key1": "value1", "key2": "value2", "key3": "value3" } }, { "parentKey": { "key1": "value1", "key2": "value2", "key3": "value3" } }, { "parentKey": { "key1": "value1", "key2": "value2", "key3": "value3" } }] } var arr = []; input.Array.forEach((obj)=>{ arr.push(obj.parentKey); }); var output = { "Array" : arr }; console.log(output);
Should work like this.
let given={ "Array":[{ "parentKey": { "key1": "value1", "key2": "value2", "key3": "value3" } },{ "parentKey": { "key1": "value1", "key2": "value2", "key3": "value3" } },{ "parentKey": { "key1": "value1", "key2": "value2", "key3": "value3" } }] } let result={ "Array":[] } given.Array.forEach((subArr, i)=>{ result.Array.push(subArr.parentKey) }) console.log(result)
And the other way around it is like this:
let given= { "Array": [ { "key1": "value1", "key2": "value2", "key3": "value3" }, { "key1": "value1", "key2": "value2", "key3": "value3" }, { "key1": "value1", "key2": "value2", "key3": "value3" } ] } let result={ "Array":[] } given.Array.forEach((subArr, i)=>{ result.Array.push({"parentKey":subArr}) }) console.log(result)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.