Reputation: 179
I have an object that I am trying to assign to different elements of an array.
I've tried to use .map() and objectKeys()/objectValues(), but I still can't figure it out.
Variables
const parameters = [{key: "0", label: "Turbidity", parameter: "turbidity", unit: "NTU"}, {key: "1", label: "Total Hardness", parameter: "totalHardness", unit: "as CaCO3"}, {key: "2", label: "Total Phosphorus", parameter: "totalPhosphorus", unit: "mg/L"}, {key: "3", label: "Total Nitrogen", parameter: "totalNitrogen", unit: "mg/L"} ];
const parameterValues = {turbidity: 2.1, totalHardness: 254}
I would like to be able to add the parameterValues to parameters as a value item to the elements that have the same parameter(label) as an elment in the array.
Expected Result
const updatedParameters = [{key: "0", label: "Turbidity", parameter: "turbidity", unit: "NTU", value: "2.1"}, {key: "1", label: "Total Hardness", parameter: "totalHardness", unit: "as CaCO3", value: "254"}, , {key: "2", label: "Total Phosphorus", parameter: "totalPhosphorus", unit: "mg/L"}, {key: "3", label: "Total Nitrogen", parameter: "totalNitrogen", unit: "mg/L"}];
Any help is greatly appreciated! Thanks
Upvotes: 1
Views: 59
Reputation: 138247
const updatedParameters = parameters.map(it => ({ ...it, value: parameterValues[it.parameter] }));
Use the parameter to look up the value in the parameter list.
Upvotes: 1
Reputation:
If I'm understanding, you want to keep the original array, but change the objects it contains. In that case, Array.find()
may help.
const parameters = [{key: "0", label: "Turbidity", parameter: "turbidity", unit: "NTU"}, {key: "1", label: "Total Hardness", parameter: "totalHardness", unit: "as CaCO3"}, {key: "2", label: "Total Phosphorus", parameter: "totalPhosphorus", unit: "mg/L"}, {key: "3", label: "Total Nitrogen", parameter: "totalNitrogen", unit: "mg/L"} ]
const addParameterValues = (valueObject) => {
Object.keys(valueObject).forEach(key => {
const parameter = parameters
.find(obj => obj.parameter === key)
parameter.value = valueObject[key]
}
}
addParameterValues({turbidity: 2.1, totalHardness: 254})
Upvotes: 0