Reputation: 659
I have a json object like this:
{
"id":"cfab8e92-025a-4070-ba1f-5bb1a8b3c9b6",
"custome-array":[
{
"date1":"12/10/2019",
"date2":"12/09/2019",
"id":"cfab8e92-025a-4070-ba1f-5bb1a8b3c9b6",
"more_data":{
"id":"59c12dbf1d41c818272198b3",
"some_no":"9204506",
"name":"blabla"
}
},
{
"date1":"12/10/2019",
"date2":"12/09/2019",
"id":"cfab8e92-025a-4070-ba1f-5bb1a8b3c9b6",
"more_data":{
"id":"59c12dbf1d41c818272198b3",
"some_no":"9204506",
"name":"blabla"
}
}
]
}
My "custome-array" is dynamic
I want to use the map function to modify this data format so that "more_data" will only store "name" rather than storing the complete object.
{
"id":"cfab8e92-025a-4070-ba1f-5bb1a8b3c9b6",
"custome-array":[
{
"date1":"12/10/2019",
"date2":"12/09/2019",
"id":"cfab8e92-025a-4070-ba1f-5bb1a8b3c9b6",
"more_data":"blabla"
},
{
"date1":"12/10/2019",
"date2":"12/09/2019",
"id":"cfab8e92-025a-4070-ba1f-5bb1a8b3c9b6",
"more_data":"blabla"
}
]
}
Upvotes: 1
Views: 304
Reputation: 1059
You can indeed use map:
const newItems = originalObject["custome-array"].map((item) => {
const newItem = item;
newItem.more_data = item.more_data.name;
return newItem;
});
const newObject = {
...originalObject,
["custome-array"]: newItems
};
console.log(newObject);// this will give you the output you want
I've added a codepen to demonstrate https://codepen.io/csteur/pen/vqZLNK
Upvotes: 0
Reputation: 11760
If you don't want to mutate the original data
const transformedData = {
id: data.id,
'custome-array': data['custome-array'].map(item => ({
...item,
more_data: item.more_data.name,
})),
};
Upvotes: 0
Reputation: 1
This works with simple forEach loop.You can mutate the original array,with forEach's
callback.
let data = {
"id": "cfab8e92-025a-4070-ba1f-5bb1a8b3c9b6",
"custome-array": [{
"date1": "12/10/2019",
"date2": "12/09/2019",
"id": "cfab8e92-025a-4070-ba1f-5bb1a8b3c9b6",
"more_data": {
"id": "59c12dbf1d41c818272198b3",
"some_no": "9204506",
"name": "blabla"
}
},
{
"date1": "12/10/2019",
"date2": "12/09/2019",
"id": "cfab8e92-025a-4070-ba1f-5bb1a8b3c9b6",
"more_data": {
"id": "59c12dbf1d41c818272198b3",
"some_no": "9204506",
"name": "blabla"
}
}
]
}
data["custome-array"].forEach(ele => {
ele["more_data"] = ele["more_data"].name;
})
console.log(data)
Upvotes: 1
Reputation: 1286
yourObject["custom-array"] = yourObject["custom-array"].map((item) => {
return {
...item,
["more_data"]: item["more_data"]["name"],
}
});
or
yourObject["custom-array"] = yourObject["custom-array"].map((item) => ({
...item,
["more_data"]: item["more_data"]["name"],
}));
Upvotes: 0