javascript - 如何使用 Javascript 中的数组值过滤对象?

标签 javascript arrays vue.js ecmascript-6

我有一个这样的对象(例如,这就是我们在 chrome 开发工具中看到该对象的方式):

obj: {
  1: {...},
  2: {...},
  3: {...},
  4: {...},
  5: {...},
}

我有一个像这样的简单数组:

arr: [1,3,5,7]

基本上我希望我的对象与数组中的键保持一致,如下所示:

obj: {
  1: {...},
  3: {...},
  5: {...},
}

目前我的代码是这样的:

var select = (arr, obj) => arr.reduce((r, e) => 
  Object.assign(r, obj[e] ? { [e]: obj[e] } : null)
, {});

var output = select(arr, obj);

我不知道为什么,但这有时有效,有时却无效。我不能使用 Jquery。 谁能帮帮我?

最佳答案

你可以使用 Object.fromEntries() , Object.entries() , Array.prototype.filter()Array.prototype.includes()过滤掉不在 arr 中的键:

const obj ={
  1: {},
  2: {},
  3: {},
  4: {},
  5: {},
};

const arr = [1, 3, 5, 7];

const filtered = Object.fromEntries(
  // Note `key` is an `string` here, thus the `+`:
  Object.entries(obj).filter(([key]) => arr.includes(+key))
);

console.log(filtered);

或者一个简单的 for 循环,for...of在这种情况下,再次使用 Array.prototype.includes()选择你想要的(而不是过滤你不需要的)和Object.prototype.hasOwnProperty()避免添加 obj 中不存在的键:

const obj ={
  1: {},
  2: {},
  3: {},
  4: {},
  5: {},
};

const arr = [1, 3, 5, 7];

const filtered = {};

for (const key of arr) { 
  // Note the `hasOwnProperty` check here to avoid adding the key `7` with a value of `undefined`:
  if (obj.hasOwnProperty(key)) filtered[key] = obj[key];
}

console.log(filtered);

或者您可以使用 Array.prototype.reduce() 做同样的事情:

const obj ={
  1: {},
  2: {},
  3: {},
  4: {},
  5: {},
};

const arr = [1, 3, 5, 7];

const filtered = arr.reduce((newObj, key) => {
  // Note we add the values to `newObj` rather than `filtered` now:
  if (obj.hasOwnProperty(key)) newObj[key] = obj[key];
  
  // And you always need to return `newObj`:
  return newObj;
}, { })

console.log(filtered);

最后,如果您已经在使用 Lodash , 你可以使用 _.pick :

const obj ={
  1: {},
  2: {},
  3: {},
  4: {},
  5: {},
};

const arr = [1, 3, 5, 7];

const filtered = _.pick(obj, arr);

console.log(filtered);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.core.min.js"></script>

关于javascript - 如何使用 Javascript 中的数组值过滤对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59591659/

相关文章:

javascript - 值为 NULL 时无法读取未定义的属性长度

javascript - 按名称、价格过滤 JQuery 列表...json 数组,JQuery.grep()

arrays - 在数组上执行 findOne() 时,Meteor 和 Mongo DB 会提供不同的结果

javascript - 指定元素的深度

java - 使用gson将json数组转换为android中的json对象?

node.js - 将文件/文件夹复制到Electron Dist文件夹

javascript - 几个大数组,还是一个包含几个变量的大数组?

javascript - 如何修复在 componentWillMount 中设置状态时的日志记录问题

vue.js - a-marker 不适用于 aframe

javascript - 向 ASP.NET Core Web API 发出发布请求时,跨域请求被阻止