Reversing an Object.entries conversion

后端 未结 5 1642
一个人的身影
一个人的身影 2020-12-17 10:03

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]) => {         


        
相关标签:
5条回答
  • 2020-12-17 10:37

    Using Object.assign with a map that maps [k,v] => {[k]: v}

    For example, the code below will only keep keys beginning with key

    var obj = {
      key: 1,
      key2: 2,
      key3: 3,
      removed: 4,
      alsoRemoved: 5
    }
    
    obj = Object.assign({}, ...Object.entries(obj)
        .filter(([k, v]) => {
            return k.startsWith('key');
        })
        .map(([k, v]) => ({[k]: v}))
    );
    
    console.log(obj);

    0 讨论(0)
  • 2020-12-17 10:38

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

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

    0 讨论(0)
  • 2020-12-17 10:42

    Using reduce with deconstruction and comma operator:

    const input = { key:'val', key2:'val2', key3:'val3' };
    
    const output = Object.entries(input)
      .filter(([k, v]) => {
         return true; // some irrelevant conditions here
      })
      .reduce((acc, [k, v]) => (acc[k] = v, acc), {});
    

    which should give the same functionality as CertainPerformance's answer with a bit more concise syntax

    0 讨论(0)
  • 2020-12-17 10:52

    If you know exactly which entries you want to exclude, you can use object deconstruction combined with spreading:

    function clean(obj) {
      const { unwanted1, unwanted2, ...wanted } = obj;
      return { ...wanted };
    }
    

    For some cases, this might be the cleanest solution.

    0 讨论(0)
  • 2020-12-17 10:56

    For new browsers, use Object.fromEntries:

    Object.fromEntries(arr); 
    

    For ES6+, with some spreading it can be a one liner.

    arr.reduce((acc,[k,v])=>({...acc,[k]:v}),{}) 
    

    Example:

    Object.entries(sampleObject) // Turn object to array
       .reduce((acc,[k,v])=>({...acc,[k]:v}),{}) // Turn it back to object.
    
    0 讨论(0)
提交回复
热议问题