本文介绍了逆转Object.entries转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我正在使用Object.entries以便从嵌套对象中获取一些值并对其进行过滤.

I am using Object.entries in order to get some values out of a nested object and filter it.

obj = Object.entries(obj)
  .filter(([k, v]) => {
    return true; // some irrelevant conditions here
  });

我的对象最终是由键和val组成的数组数组.

My object ends up as an array of arrays, of keys and vals.

[['key1', val]['key2', val']['key3', val]]

是否有一种直接的方法可以将这些映射回一个对象?原始对象结构为:

Is there a straightforward way to map these back into an object? The original object structure is:

{ key:val, key2:val2, key3:val3 }

推荐答案

当然,只需使用.reduce分配给新对象即可:

Sure, just use .reduce to assign to a new object:

const input = { key:'val', key2:'val2', key3:'val3' };

const output = Object.entries(input)
  .filter(([k, v]) => {
    return true; // some irrelevant conditions here
  })
  .reduce((accum, [k, v]) => {
    accum[k] = v;
    return accum;
  }, {});
console.log(output);

在现代浏览器中,您还可以使用 Object.fromEntries ,这使这一切变得更加容易-您只需传递一个条目数组,它就会根据这些条目创建对象.

In modern browsers, you can also use Object.fromEntries which makes this even easier - you can just pass an array of entries, and it'll create the object from those entries.

const input = { key:'val', key2:'val2', key3:'val3' };

const output = Object.fromEntries(
  Object.entries(input)
    .filter(([k, v]) => {
      return true; // some irrelevant conditions here
    })
);
console.log(output);

这篇关于逆转Object.entries转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 12:10