I am trying to map through the data.scales array of objects and display the values in the obj createvalues array as shown in the output. I cannot quite figure this out. I have to make sure I do not delete the values existing in the createValues array
const obj = {
projectId: 0,
gridId: 0,
createValues: [
{
field: 1111,
value: "cool"
},
{
field: 13341,
value: "cl"
},
{
field: 1111,
value: "cool"
}
]
};
const data = {
scales:[
{
ScaleId:109165,
Value:"LOW"
},
{
ScaleId:109165,
Value:"LOW"
}
]
};
const result = Object.entries(data.scales).map(([key, value]) => ({
field: data.scales.value,
value: data.scales.value
}));
console.log(result)
obj.createValues=
The output expected is this one :
const output = {
projectId: 0,
gridId: 0,
createValues: [
{
field: 1111,
value: "cool"
},
{
field: 13341,
value: "cl"
},
{
field: 1111,
value: "cool"
}
{
field: 109165,
value: "LOW"
},
{
field: 109165,
value: "LOW"
}
]
};
You were almost there, continuing from your solution you can do
Solution 1
const results = Object.entries(data.scales).map(([key, value]) => {
return ({
field: value.ScaleId,
value: value.Value
})
});
obj.createValues = [...obj.createValues, ...results]; // Use spread operator to combine two arrays
Solution 2
You can also make use of array.map method of to loop directly through scales
This method allows you to loop through the array elements. You can find the value in the createValues array of objects and if does not exists you can then push the new object into obj.createValues.
I have only checked for value, you can add condition for field ID if needed in find method.
data.scales.map(sc => {
if(obj.createValues.find(v => v.value !== sc.Value)) {
obj.createValues.push({field: sc.ScaleId, value: sc.Value})
}
})
Solution Snippet:
const obj = {
projectId: 0,
gridId: 0,
createValues: [
{
field: 1111,
value: "cool"
},
{
field: 13341,
value: "cl"
},
{
field: 1111,
value: "cool"
}
]
};
const data = {
scales:[
{
ScaleId:109165,
Value:"LOW"
},
{
ScaleId:109165,
Value:"LOW"
}
]
};
data.scales.map(sc => {
if(obj.createValues.find(v => v.value !== sc.Value)) {
obj.createValues.push({field: sc.ScaleId, value: sc.Value})
}
})
console.log(obj)