首页 > 解决方案 > 过滤嵌套对象

问题描述

我收到一个如下所示的对象:

 this.tokensData = {
    O: {
        id: 0,
        name: value1,
        organization: organization1,
        ...,
       },
    1: {
        id: 1,
        name: value1,
        organization: organization1,
        ...,
        },
    2: {
        id: 2,
        name: value2,
        organization: organization2,
        ...,
        },
    ...
   }

我想过滤id并删除Object与我id从. 到目前为止我尝试了什么:idstore

const filteredObject = Object.keys(this.tokensData).map((token) => {
  if (this.$store.state.id !== this.tokensData[token].id) {
    return this.tokensData[token];
  }
});

这取代了Object-undefined这将适用于我的目的,但显然并不理想。任何帮助深表感谢!

标签: javascriptobjectfilter

解决方案


尝试使用Object.entries然后Object.fromEntries()从键值对列表中创建一个对象:

let store = [0 , 1];

const result = Object.entries(tokensData).filter(([k, v]) => !store.some(s => s == v.id));

console.log(Object.fromEntries(result));

一个例子:

let tokensData = {
   O: {
       id: 0,
       name: '',
       organization: '',
      },
   1: {
       id: 1,
       name: '',
       organization: '',
       },
   2: {
       id: 2,
       name: '',
       organization: '',
       }
  }

let store = [0 , 1];

const result = Object.entries(tokensData).filter(([k, v]) => !store.some(s => s == v.id));

console.log(Object.fromEntries(result));


推荐阅读