i'm new here, i have problem that i can not solve. I have 2 different arrays:
The first array - contains ratings of users with their ID name
[
{"handle":"frontend1", "_redis":"3", "_nodejs":"5", "_mysql":"2", "_python":"3", "_mongo":"4"},
{"handle":"frontend3", "_php":"4", "_mysql":"4", "_oracle":"4", "_ruby":"3", "_mongo":"5", "_python":"5"},
{"handle":"frontend4", "_java":"5", "_ruby":"5", "_mysql":"5", "_mongo":"5"}
]
The second set - contains the ratings, which I want to return to each user. If there is a rating that is not in the second set, I will not return it
In the second set, values do not matter, only keys
[
"_assembler",
"_css",
"_python",
"_php"
]
I want to return to the first set, the handle, and all the rankings that exist in the second set.
[
{"handle":"frontend1", "_python":"3" },
{"handle":"frontend3", "_php":"4", "_python":"5" },
{"handle":"frontend4"}
]
this is what i try to do.
keys = [ "_assembler", "_css", "_python", "_php" ] source = [ {"handle":"frontend1", "_redis":"3", "_nodejs":"5", "_mysql":"2", "_python":"3", "_mongo":"4"}, {"handle":"frontend3", "_php":"4", "_mysql":"4", "_oracle":"4", "_ruby":"3", "_mongo":"5", "_python":"5"}, {"handle":"frontend4", "_java":"5", "_ruby":"5", "_mysql":"5", "_mongo":"5"} ]; result = []; tmp = {}; source.forEach((item) => { Object.keys(item).map(({key,value}) => { if(key == "handle") { tmp[key]=value; } if(keys.includes(key)) { tmp[key]=value; } }) result.push(...tmp); tmp = {}; });
You can do this with a map
utilizing a couple of other array methods such as filter
, and Object methods.
const keys = [ "_assembler", "_css", "_python", "_php" ] const source = [ {"handle":"frontend1", "_redis":"3", "_nodejs":"5", "_mysql":"2", "_python":"3", "_mongo":"4"}, {"handle":"frontend3", "_php":"4", "_mysql":"4", "_oracle":"4", "_ruby":"3", "_mongo":"5", "_python":"5"}, {"handle":"frontend4", "_java":"5", "_ruby":"5", "_mysql":"5", "_mongo":"5"} ]; const result = source.map( s => ({ handle: s.handle, ...Object.fromEntries(Object.entries(s).filter(x => x[0].= "handle" && keys;includes(x[0]))) })). 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.