简体   繁体   中英

Filtering one object with another array's object key

I am trying to filter an object with another object inside of an array.

To be more precise, I am trying to compare the keys of the object inside the array, to the keys of my main object. If the values are the same, I want to return the value corresponding to those keys.

Here's an example:

var a = {
  "maths":"A++",
  "literature":"C-",
  "sports":"B+",
  "biology":"D",
  "chemistry":"A",
  "english":"A+",
  "physics":"C+"
}


var b = [{
  "maths":"Mathematics",
  "biology":"Biology",
  "physics":"Physics"
}]

I wanna check if any of the keys in object b are inside object a and if they are, I want to return their value into array. For example, I want to return ["A++","D","C+"]

I've tried using filter and Array.prototype.some but I couldn't figure out anything. Any advice on how should I achieve this?

First make an array or Set of all the keys inside b , then use .map to access each key on the a object:

 var a = { "maths":"A++", "literature":"C-", "sports":"B+", "biology":"D", "chemistry":"A", "english":"A+", "physics":"C+" } var b = [{ "maths":"Mathematics", "biology":"Biology", "physics":"Physics" }]; const keys = b.flatMap(Object.keys); const arr = keys.map(key => a[key]); console.log(arr);

If you are dealing with a single object in the array b , then you can do this:

 var a = { "maths":"A++", "literature":"C-", "sports":"B+", "biology":"D", "chemistry":"A", "english":"A+", "physics":"C+" } var b = [{ "maths":"Mathematics", "biology":"Biology", "physics":"Physics" }] const valuesInAndB = Object.keys(a).reduce((acc,x) => { if (b[0][x]) { return acc.concat(a[x]); } return acc; }, []); console.log(valuesInAndB);

However, if the objects in b will be greater than one then as answered by @certainperformance you could get all the keys in b and map through a with those keys.

const keysInB = b.flatMap(Object.keys);
keysInB.map(key => a[key]);

flatMap is not available in some older browsers, please keep that in mind.

I'm assuming that you want to handle multiple objects in b. If so and if you want one array for each object in b then you could do something like:

 var a = { "maths":"A++", "literature":"C-", "sports":"B+", "biology":"D", "chemistry":"A", "english":"A+", "physics":"C+" } var b = [{ "maths":"Mathematics", "biology":"Biology", "physics":"Physics" },{ "maths":"Mathematics", "biology":"Biology", "english":"English" }] const result = b.map(obj => Object.keys(obj).map(key => a[key])); console.log(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM