I have an array obj, and I am and Im adding another object links and I am creating a serie array in the object. I want to create another movie array after the serie array.
const obj = {
projectId: 0,
gridId: 0,
createValues: [
{
field: "string",
value: "string"
}
]
};
const dataCompo = {
"model-10389": 164703,
"model-10388": 164704,
"model-10387": 164705
};
const dataTraca = {
"model-10389": [1656, 1234, 1245],
"model-10384": [1656, 1234, 1245],
"model-10383": [1656, 1234, 1245],
};
const ser = Object.entries(dataCompo).map(([key, value]) => ({
modelId: key.substring(6),
id: value
}));
obj.links = {
serie: ser
};
const mov = Object.entries(dataTraca).map(([key,value]) => ({
modelId: key.substring(6),
ids: value
}));
obj.links = {
movie: mov
};
console.log(obj);
The thing is like this it is remplacing the whole links object and serie array with the movie one. I cannot quite figure how to use the spread operator.
I have managed to do it in one line like this:
obj.links = { serie: ser, movie:mov };
However I would like to do it seperately just like above
you can do something like this
const obj = { projectId: 0, gridId: 0, createValues: [{ field: "string", value: "string" }] }; const dataCompo = { "model-10389": 164703, "model-10388": 164704, "model-10387": 164705 }; const dataTraca = { "model-10389": [1656, 1234, 1245], "model-10384": [1656, 1234, 1245], "model-10383": [1656, 1234, 1245], }; const newData = [ ['movie', dataCompo], ['serie', dataTraca] ].reduce((res, [key, value]) => { return {...res, [key]: Object.entries(value).map(([key, value]) => ({ modelId: key.substring(6), id: value })) } }, obj) console.log(newData)
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.