0

I am aware of es6/es7 features and tried to achieve the output using these but none of them is working.

what I have:

x = { a: 10, b: 20, c: 30, f:56, n:99}

now want a new object which have {a, n} only i.e. {a:10,n:99}

trial 1

let y = {a: 0, n: 0};

y = Object.assign({}, y, x);

trial 2

let {a: 0, n:0 } = x;

trial 3

{a, n, ...rest} = x;

but it gives two separate variables with the value, not a complete object

but nothing is working out.


update

after checking answers to the given asnwer of duplicate link, all they are eliminating rest of property if they do not exist in the source array or value replaced by undefined

I want to preserve the keys with value which do not exist in the source array.

Here are my efforts but it seems to be not good. also, I have object not the array

I need to use Object.assign() somewhere but not able where to?

 (function() {
       const pick = (o, fields) => {
            return fields.reduce((a, x, ca) => {
                if (o.hasOwnProperty(x)) a[x] = o[x];
                return a;
            }, {});
        }
       
     
     let defaultObject = {id: 0, selected: false, other: 'set'};
    
     let sourceArray = {id: '10', name: 'Name', selected: true};
    
     let output = pick(sourceArray, Object.keys(defaultObject)); 
    
      console.log("output", output);
    }());

actual output

{     
      "id": "10",
      "selected": true
}

expected output:

{
  "id": "10",
  "selected": true, 
  "other": "set"
}
Community
  • 1
  • 1
diEcho
  • 50,018
  • 37
  • 156
  • 230
  • Thank you for the link; I was not able to find as I was not aware the exact terms to search. I also look at the answers of the link, they have good solutions but that is not exactly duplicates. – diEcho May 21 '18 at 04:51
  • my problem is lil bit diffrent , I need to store the object property which has not been there in source array . let me update my question. – diEcho May 21 '18 at 04:53

0 Answers0