I have an array of color like this
var colors = ['yellow','blue']
And my data base return me
var db = [{name : "Paul", yellow : "it's yellow or not", pink : null, red : null,blue:"it's darkblue"},{name : "Eva", yellow : "it's yellow of course", pink : null, red : null,blue:"it's light blue"}]
So I wanted to show in an other array only the color which are in the color array (the first array)
This is what I want
var newArray = [{name : "Paul", yellow : "it's yellow or not", blue:"it's darkblue"},{name : "Eva", yellow : "it's yellow of course",blue:"it's light blue"}]
This is what I do
var colors = ['yellow','blue']
var db = [{name : "Paul", yellow : "it's yellow or not", pink : null, red : null,blue:"it's darkblue"},{name : "Eva", yellow : "it's yellow of course", pink : null, red : null,blue:"it's light blue"}]
var newArray = db.map(x => {
var selectedColors = colors.map(y => { return { [y]: x[y] } })
return {
name : x.name ,
...selectedColors
}
})
But i have something like this (example with 1 row) :
{
0 : {yellow : "it's yellow or not"},
1 : {blue: "it's darkblue"},
name : "Paul"
}
but I want this
{
yellow : "it's yellow or not",
blue: "it's darkblue",
name : "Paul"
}
5
Answers
For each object in
db
, iterate overcolors
and take a property from the object that corresponds to the current element ofcolors
:If you care about number of lines, you could use
.reduce
method instead:joining objects you can not have identical key names for this name you only see it 1 time
to merge your items into one use this code :
You are on the right track. Either use
Object.assign()
as the last step:Try it:
…or use
Array#reduce()
:This is roughly equivalent to:
Try it:
The main issue with the code is that you cannot define an object if you don’t know how many fields you want. You can set a variable name and value by using square brackets (see computed property names).
However this doesn’t help you much if you don’t know how many (if any)
colorVariable
s you have.In this scenario you want to use
Object.fromEntries()
to convert a list of key/value-pairs to an object.To create this list we can
map()
over a list of fields that you want to extract.To do this for every object in
db
you’ll want tomap()
over each object indb
as well.Note that:
Is short for:
You can reduce you
db
array like this (some explanation in comments):