如何使用JavaScript根据嵌套的color值从JSON数组中提取目标对象
解决方法:根据嵌套color值提取目标对象
嘿,我来帮你搞定这个问题!首先看你的数据结构,每个顶层元素都是带数字键的对象,里面的cat.string数组藏着我们要找的color值。我们需要过滤出包含指定color(这里是"Yellow",不区分大小写)的项,并且调整结构让输出符合你的预期。
首先先修正一下原数据的语法小问题(最后多了个逗号),然后用下面的代码实现:
const data = [ {0: {id: "1", cat:{string:[{color:"yellow",weight:"10"},{color:"orange",weight:"10"}]}}}, {1: {id: "1", cat:{string:[{color:"blue",weight:"10"},{color:"orange",weight:"10"}]}}}, {2: {id: "1", cat:{string:[{color:"white",weight:"10"},{color:"orange",weight:"10"}]}}}, {3: {id: "1", cat:{string:[{color:"blue",weight:"10"},{color:"orange",weight:"10"}]}}} ]; const targetColor = "Yellow"; const result = data.reduce((acc, item) => { // 获取当前项的数字键(0、1、2、3) const key = Object.keys(item)[0]; const currentObj = item[key]; // 过滤出颜色匹配的项,忽略大小写 const matchedColors = currentObj.cat.string.filter(colorItem => colorItem.color.toLowerCase() === targetColor.toLowerCase() ); // 只有当有匹配结果时,才添加到结果数组中 if (matchedColors.length > 0) { acc.push({ [key]: { ...currentObj, cat: matchedColors // 替换原cat结构为过滤后的数组,符合你的输出要求 } }); } return acc; }, []); console.log(result);
代码说明:
- 用
reduce遍历原数组,逐步构建结果数组,比单纯的filter更灵活,方便我们同时修改输出结构。 - 用
Object.keys(item)[0]拿到每个顶层对象的唯一数字键,因为每个元素只有一个键值对。 filter配合toLowerCase()实现不区分大小写的颜色匹配,这样不管输入是"yellow"还是"Yellow"都能准确命中。- 构造新对象时,用扩展运算符
...currentObj保留原有的属性(比如id),然后把cat替换成过滤后的颜色数组,完全贴合你期望的输出结构。
运行这段代码后,输出结果就是:
[ { "0": { "id": "1", "cat": [ { "color": "yellow", "weight": "10" } ] } } ]
另外注意你期望输出里的country和address字段在原数据里不存在,所以我保留了原数据里的id字段,如果需要添加额外字段,直接在构造对象的时候补充即可。
内容的提问来源于stack exchange,提问作者Powershell-Guy
相关产品推荐
相关产品推荐

