如何通过键过滤JSON对象?重命名键后过滤操作无效
过滤重命名后的JSON对象键值对
首先修正你现有代码的一个问题:你用map循环时,每次都把reassaignedKeys覆盖成当前条目的对象,最终只会得到最后一个entries的结果。正确的做法是把所有重命名后的对象存入数组:
// 生成所有重命名后的对象数组 const renamedObjects = props.data.map(entries => ({ Owner: entries[0], ApplicationId: entries[1], ApplicationName: entries[2], Status: entries[3], DeploymentStatus: entries[4], Classification: entries[5], PersonalBindle: entries[6], PerviouslyCertified: entries[7], Goal: entries[8] }));
接下来解决键过滤的问题:Object.keys.filter只是筛选出符合条件的键名数组,不会自动生成新的过滤后对象。你需要基于这些筛选后的键,重新构建对象。
方法1:使用Object.fromEntries(ES2019+)
这是最简洁的方式,先把对象转成键值对数组,过滤后再转回对象:
// 定义需要保留的键列表 const allowedKeys = ['Owner', 'ApplicationId', 'Status']; // 替换成你要保留的键 // 过滤每个对象的键值对 const filteredObjects = renamedObjects.map(obj => { return Object.fromEntries( Object.entries(obj).filter(([key]) => allowedKeys.includes(key)) ); }); console.log(filteredObjects);
方法2:兼容旧环境的写法
如果你的运行环境不支持Object.fromEntries,可以手动遍历允许的键来构建新对象:
const allowedKeys = ['Owner', 'ApplicationId', 'Status']; const filteredObjects = renamedObjects.map(obj => { const filteredObj = {}; allowedKeys.forEach(key => { // 确保原对象存在该键时才添加 if (obj.hasOwnProperty(key)) { filteredObj[key] = obj[key]; } }); return filteredObj; }); console.log(filteredObjects);
这样就能得到只包含你指定键的对象数组了。
内容的提问来源于stack exchange,提问作者Zubair Amjad
相关产品推荐
相关产品推荐

