gpt4 book ai didi

javascript - 根据嵌套对象中存在的特定值过滤 JSON 对象

转载 作者:行者123 更新时间:2023-11-30 19:07:45 26 4
gpt4 key购买 nike

您好,我正在尝试过滤我的 JSON 响应以仅获取那些 >=0 的值。

My response is below :

  {
"response": [{
"countryId": {
"id": "10050020025",
"idScheme": "externalId"
},
"processedDateTime": "2019-11-07 05:39:09",
"AAE": [{
"amount": "1000",
"currencyCode": "USD"
}],
"TAE": [{
"amount": "0",
"currencyCode": "USD"
}]
},
{
"countryId": {
"id": "10291520071",
"idScheme": "InternalId"
},
"processedDateTime": "2019-02-03 08:21:22",
"AAE": [{
"amount": "0",
"currencyCode": "USD"
}],
"TAE": [{
"amount": "-2001",
"currencyCode": "USD"
}]
}
]
}

I am trying to achieve :

{
"response": [{
"countryId": {
"id": "10050020025",
"idScheme": "externalId"
},
"processedDateTime": "2019-11-07 05:39:09",
"AAE": [{
"amount": "1000",
"currencyCode": "USD"
}]
},
{
"countryId": {
"id": "10291520071",
"idScheme": "InternalId"
},
"processedDateTime": "2019-02-03 08:21:22",
}
]
}

我正在尝试使用 es6 中的 map & filter 来实现此目的,但效果不佳,因为我不知道该怎么做。到目前为止,我正在尝试一些硬编码的方法。

const outputResponse = response
.map(value => value)
.filter(value => value.AAE[0].amount !== '0')

但它会删除没有数量“0”的整个对象。

感谢任何帮助。

最佳答案

您只需要一个 Array#map() method 调用以映射所有 response 对象并删除 AAETAE 或目标 keys 值有 数量 < 0:

let keys = ["AAE", "TAE"];

let result = data.response.map(val => {
keys.forEach(key => {
if (val[key] && val[key].some(x => +x.amount <= 0)) {
delete val[key];
}
});
return val;
});

演示:

let keys = ["AAE", "TAE"];

let data = {
"response": [{
"countryId": {
"id": "10050020025",
"idScheme": "externalId"
},
"processedDateTime": "2019-11-07 05:39:09",
"AAE": [{
"amount": "1000",
"currencyCode": "USD"
}],
"TAE": [{
"amount": "0",
"currencyCode": "USD"
}]
},
{
"countryId": {
"id": "10291520071",
"idScheme": "InternalId"
},
"processedDateTime": "2019-02-03 08:21:22",
"AAE": [{
"amount": "0",
"currencyCode": "USD"
}],
"TAE": [{
"amount": "-2001",
"currencyCode": "USD"
}]
}
]
};

let result = data.response.map(val => {
keys.forEach(key => {
if (val[key] && val[key].some(x => +x.amount <= 0)) {
delete val[key];
}
});
return val;
});

console.log(result);

关于javascript - 根据嵌套对象中存在的特定值过滤 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58815732/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com