Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
181 views
in Technique[技术] by (71.8m points)

javascript - Reversing an Object.entries conversion

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
  });

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 }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...