0

Could you please help in achieve below output compare var1 and var2 and obtain output based of var2 where key are provided in string of array

var1 = {a:1, b:2, c:3, d:4};
var2 = ['a', 'd'];

Output should be:

var3 = {a:1, d:4};

4 Answers 4

3
const var3 = var2.reduce((acc, cur) => {
  if (var1[cur]) {
    acc[cur] = var1[cur];
  }
  return acc;
}, {})

https://jsfiddle.net/chp510nj/

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the solution i have use case. where key is not available in array for example. var var1 = {a:1,b:2,c:3,d:4}; var var2 =['a','d','f']; i have output like var3 = {a:1, d:4};
@GauthamShetty a simple if will solve that. see edit
0

Using .forEach

var var1 = {a:1,b:2,c:3,d:4}; var var2 =['a','d'];
var var3 = {};

var2.forEach(i=>{
 var3[i] = var1[i]
})


console.log(var3)

2 Comments

Thanks for the solution i have use case. where key is not available in array for example. var var1 = {a:1,b:2,c:3,d:4}; var var2 =['a','d','f']; i have output like var3 = {a:1, d:4};
I didn’t get you. The case you provided would still work with this solution.
0

You can use Object.entries and iterate

var1 = {a:1,b:2,c:3,d:4}; var2 =['a','d'];
o={}
for(let [k,v] of Object.entries(var1)){
  var2.forEach(x=>{if(k==x){
        o[k]=v
  }})
}
console.log(o)

1 Comment

Thanks for the solution i have use case. where key is not available in array for example. var var1 = {a:1,b:2,c:3,d:4}; var var2 =['a','d','f']; i have output like var3 = {a:1, d:4};
0

You can .map() each key in var2 to an object containing the key and its associated value. From that mapped array, you can assign each object to an object using Object.assign():

const var1 = {a:1,b:2,c:3,d:4};
const var2 = ['a','d', 'f'];

const var3 = Object.assign({}, ...var2.map(id => id in var1 ? {[id]: var1[id]} : {}));
console.log(var3);

Another approach could be to use Object.fromEntries() if you can support it:

const var1 = {a:1,b:2,c:3,d:4};
const var2 = ['a','d', 'f'];

const var3 = Object.fromEntries(var2.filter(id => id in var1).map(id => [id, var1[id]]));
console.log(var3);

2 Comments

Thanks for the solution i have use case. where key is not available in array for example. var var1 = {a:1,b:2,c:3,d:4}; var var2 =['a','d','f']; i have output like var3 = {a:1, d:4};
@GauthamShetty I've updated my answer to handle these cases

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.