gpt4 book ai didi

Javascript 对象,返回包含嵌套数组中值的更新对象

转载 作者:行者123 更新时间:2023-11-30 19:49:47 25 4
gpt4 key购买 nike

我有以下对象:

{
"id": 2,
"name": "tes name",
"status": 0,
"categories": [
{
"category_id": 1,
"name": "taxes",
"description": "taxes",
"keys": [
{
"key_id": 1,
"value": "preset unique value if not overridden, real text value"
},
{
"key_id": 2,
"value": "test name"
}
]
},
{
"category_id": 2,
"name": "surcharges",
"description": "surcharges",
"keys": [
{
"key_id": 3,
"value": "preset value if not overridden, real text value"
},
{
"key_id": 5,
"value": ""
}
]
},
{
"category_id": 3,
"name": "errors",
"description": "errors",
"keys": [
{
"key_id": 6,
"value": "preset value if not overridden, real text value"
},
{
"key_id": 10,
"value": "unique value to test search"
}
]
}
]
}

我需要做的是根据以下条件更新对象:如果只有 key.value 包含字符串 'unique',则它必须包含键数组中的键,否则数组不能包含该键在键数组中。

预期输出是:

{
"id": 2,
"name": "tes name",
"status": 0,
"categories": [
{
"category_id": 1,
"name": "taxes",
"description": "taxes",
"keys": [
{
"key_id": 1,
"value": "preset unique value if not overridden, real text value"
}
]
},
{
"category_id": 3,
"name": "errors",
"description": "errors",
"keys": [
{
"key_id": 10,
"value": "unique value to test search"
}
]
}
]
}

我试过嵌套过滤器,但它对我不起作用,总是得到相同的对象。

我的代码:

var result = obj.categories.filter(function(category) {
return category.keys.filter(function(key) {
return key.value.includes(action.payload)
});
});

有什么建议或我哪里出错了吗?

最佳答案

您可以采用嵌套方法并通过检查嵌套的 filterd 数组来减少数组。

这个解决方案不会改变原始数据。

var data = { id: 2, name: "tes name", status: 0, categories: [{ category_id: 1, name: "taxes", description: "taxes", keys: [{ key_id: 1, value: "preset unique value if not overridden, real text value" }, { key_id: 2, value: "test name" }] }, { category_id: 2, name: "surcharges", description: "surcharges", keys: [{ key_id: 3, value: "preset value if not overridden, real text value" }, { key_id: 5, value: "" }] }, { category_id: 3, name: "errors", description: "errors", keys: [{ key_id: 6, value: "preset value if not overridden, real text value" }, { key_id: 10, value: "unique value to test search" }] }] },
filtered = Object.assign({}, data, {
categories: data.categories.reduce((r, o) => {
var keys = o.keys.filter(({ value }) => value.includes('unique'));
if (keys.length) {
r.push(Object.assign({}, o, { keys }));
}
return r;
}, [])
});

console.log(filtered);
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于Javascript 对象,返回包含嵌套数组中值的更新对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54591610/

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