For a project i need to push the values of an array into every object in another array.
What i have so far:
closed_status = [{
"project_no": 5,
"priority": 3,
"s_status": "S8",
"project_Status: closed"
},
{
"project_no": 8,
"priority": 1,
"s_status": "S5",
"project_Status: closed"
},
{
"project_no": 12,
"priority": 2,
"s_status": "S2",
"project_Status: closed"
}
]
str = [
"Value 1",
"Value 2",
"Value 3",
]
let result = []
closed_status.forEach((obj) => {
str.forEach((newValue) => {
result.push({ ...obj,
newValue
})
})
})
…and this is the result i get
result = [{
"project_no" : 5,
"priority" : 3,
"s_status": "S8",
"project_Status: closed",
"newValue": "Value 1"
},
{
"project_no" : 5,
"priority" : 3,
"s_status": "S8",
"project_Status: closed",
"newValue": "Value 2"
},
{
"project_no" : 5,
"priority" : 3,
"s_status": "S8",
"project_Status: closed",
"newValue": "Value 3"
},
{
"project_no" : 8,
"priority" : 1,
"s_status": "S5",
"project_Status: closed",
"newValue": "Value 1",
},
{
"project_no" : 8,
"priority" : 1,
"s_status": "S5",
"project_Status: closed",
"newValue": "Value 2",
}]
…and so on…
But what i am trying to get is:
{
"project_no" : 5,
"priority" : 3,
"s_status": "S8",
"project_Status: closed",
"newValue": "Value 1",
},
{
"project_no" : 8,
"priority" : 1,
"s_status": "S5",
"project_Status: closed",
"newValue": "Value 2",
},
{
"project_no" : 12,
"priority" : 2,
"s_status": "S2",
"project_Status: closed",
"newValue": "Value 3",
},
Anyone knows where my mistake is?
Thanks in advance
4
Answers
Assuming, that
closed_status
andstr
always have the same length, which it looks like from your example and wanted result, then you could do the following.I guess you want to fill the array of objects with the values of str.
You could do this by keeping track of the index:
If you’re sure
str
andclosed_status
have the same amount of items, you could usestr.shift()
to shift out a single value that you spread into the original object.The following solution assumes the first array is longer than the second. However, the lengths are always the same then
i < str.length ? i : i % str.length
can be replaced byi
.