我有一个像这样的json对象:
{
"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"
}
}
]
}
我的“客户数组”是动态的
我想使用map函数修改此数据格式,以便“ more_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":"blabla"
},
{
"date1":"12/10/2019",
"date2":"12/09/2019",
"id":"cfab8e92-025a-4070-ba1f-5bb1a8b3c9b6",
"more_data":"blabla"
}
]
}
答案 0 :(得分:1)
这适用于简单的forEach循环。您可以使用messagesFetchAction()
回调来使原始数组发生变化。
// messageActions.js
export const messagesFetchAction = (data) => {
systemState.setState({isLoggedIn: false}); // <=====
return {
type: MESSAGES_FETCH,
data: data
}
}
答案 1 :(得分:0)
您确实可以使用地图:
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
我添加了一个代码笔来演示https://codepen.io/csteur/pen/vqZLNK
答案 2 :(得分:0)
yourObject["custom-array"] = yourObject["custom-array"].map((item) => {
return {
...item,
["more_data"]: item["more_data"]["name"],
}
});
或
yourObject["custom-array"] = yourObject["custom-array"].map((item) => ({
...item,
["more_data"]: item["more_data"]["name"],
}));
答案 3 :(得分:0)
如果您不想变异原始数据
const transformedData = {
id: data.id,
'custome-array': data['custome-array'].map(item => ({
...item,
more_data: item.more_data.name,
})),
};