我正在尝试将数组中包含多个对象的数组弄平。它一直将其展平为一个阵列。我希望它在数组中具有多个对象,但也希望所有内容都扁平化,除去键和值之外的所有内容。
这是当前名为“ livedata”的数组。
[
{
"earningsFileId": {
"value": 1234
},
"paymentType": {
"value": "Session",
"errors": [
{
"id": 802462,
"message": "Invalid Combination",
"status": "Processing"
}
]
},
"detailStatus": {
"value": "Processing"
}
},
{
"earningsFileId": {
"value": 5678
},
"paymentType": {
"value": "Session",
"errors": [
{
"id": 802462,
"message": "Invalid Combination",
"status": "Processing"
}
]
},
"detailStatus": {
"value": "Processing"
}
}
]
这是我要实现的输出。
[
{
"earningsFileId": 1234,
"paymentType": "Session",
"detailStatus": "Processing"
},
{
"earningsFileId": 1234,
"paymentType": "Session",
"detailStatus": "Processing"
}
]
data = [];
Object.values(livedata).map((value, keys) => {
Object.keys(value).forEach((key) => {
data[key] = livedata[keys][key]['value']
})
});
答案 0 :(得分:2)
您需要根据livedata
中的每个对象创建一个新的“扁平化”对象。您可以使用Object.entries
和reduce
将每个键值对获取所需对象的数组:
const livedata = [{
"earningsFileId": {
"value": 1234
},
"paymentType": {
"value": "Session",
"errors": [{
"id": 802462,
"message": "Invalid Combination",
"status": "Processing"
}]
},
"detailStatus": {
"value": "Processing"
}
},
{
"earningsFileId": {
"value": 5678
},
"paymentType": {
"value": "Session",
"errors": [{
"id": 802462,
"message": "Invalid Combination",
"status": "Processing"
}]
},
"detailStatus": {
"value": "Processing"
}
}
];
const result = livedata.map(d =>
Object.entries(d).reduce((acc, [k, v]) => {
acc[k] = v.value;
return acc;
}, {}))
console.log(result);