最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Alternative to Object.fromEntries? - Stack Overflow

programmeradmin2浏览0评论

I receive an object like this:

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

I then filter by id and remove the Object which id matches the id I receive from the store like so:

  filterOutDeleted(ids: any[], data: object,) {
    const remainingItems = Object.fromEntries(Object.entries(data)
      .filter(([, item]) => !ids.some(id => id === item.id)));

    const rows = Object.keys(remainingItems).map((item) => remainingItems[item]);
    return rows;
  }

Unfortunately, I'm getting an error when building stating Property 'fromEntries' does not exist on type 'ObjectConstructor' and I am unable to make changes in the tsconfig file at this point. Is there an alternative for fromEntries for this case? Any help is much appreciated!

I receive an object like this:

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

I then filter by id and remove the Object which id matches the id I receive from the store like so:

  filterOutDeleted(ids: any[], data: object,) {
    const remainingItems = Object.fromEntries(Object.entries(data)
      .filter(([, item]) => !ids.some(id => id === item.id)));

    const rows = Object.keys(remainingItems).map((item) => remainingItems[item]);
    return rows;
  }

Unfortunately, I'm getting an error when building stating Property 'fromEntries' does not exist on type 'ObjectConstructor' and I am unable to make changes in the tsconfig file at this point. Is there an alternative for fromEntries for this case? Any help is much appreciated!

Share Improve this question asked Apr 17, 2020 at 6:57 suuuriamsuuuriam 75714 silver badges27 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

Create the object outside instead, and for every entry that passes the test, assign it to the object manually.

Also note that you can decrease the putational plexity by constructing a Set of the ids in advance:

const filterOutDeleted = (ids: any[], data: object) => {
  const idsSet = new Set(ids);
  const newObj = {};
  for (const [key, val] of Object.entries(data)) {
    if (!idsSet.has(val.id)) {
      newObj[key] = val;
    }
  }
  return newObj;
};
发布评论

评论列表(0)

  1. 暂无评论