如何通过指定数组筛选对象数组特定键并重组对象?
解决JavaScript对象属性筛选与结构重组问题
你的核心问题在于:当前代码里的selectedColors是一个包含多个独立对象的数组,展开数组时会把数组索引(0、1)作为键,导致结构不符合预期。需要把颜色对应的键值对合并成单一对象后,再和name属性合并。
方法一:用reduce合并颜色属性
这是兼容性较好的写法,适合所有现代浏览器:
var colors = ['yellow','blue'] var db = [{name : "Paul", yellow : "it's yellow or not", pink : null, red : null,blue:"it's darkblue"},{name : "Eva", yellow : "it's yellow of course", pink : null, red : null,blue:"it's light blue"}] var newArray = db.map(x => { // 用reduce遍历颜色数组,把键值对合并到空对象里 var selectedColors = colors.reduce((result, color) => { result[color] = x[color]; return result; }, {}); return { name: x.name, ...selectedColors }; });
方法二:用Object.fromEntries(ES2019+)
如果你的运行环境支持ES2019及以上,这个写法更简洁:
var colors = ['yellow','blue'] var db = [{name : "Paul", yellow : "it's yellow or not", pink : null, red : null,blue:"it's darkblue"},{name : "Eva", yellow : "it's yellow of course", pink : null, red : null,blue:"it's light blue"}] var newArray = db.map(x => { // 把颜色转换成[key, value]格式的数组,再直接转成对象 var selectedColors = Object.fromEntries( colors.map(color => [color, x[color]]) ); return { name: x.name, ...selectedColors }; });
结果验证
两种方法都会生成你需要的结构:
[ {name : "Paul", yellow : "it's yellow or not", blue:"it's darkblue"}, {name : "Eva", yellow : "it's yellow of course", blue:"it's light blue"} ]
原代码问题解析
原代码中colors.map(...)返回的是[{yellow: ...}, {blue: ...}]这样的数组,当用...selectedColors展开时,JavaScript会把数组的索引作为对象键,所以才出现了0: {...}, 1: {...}的异常结构。而上面的方法都是将数组转换成包含所有颜色键值对的单一对象,展开后就能直接合并到结果对象中。
内容的提问来源于stack exchange,提问作者user10863293
相关产品推荐
相关产品推荐

