1

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

0

2 Answers 2

1
 const updatedParameters = parameters.map(it => ({ ...it, value: parameterValues[it.parameter] }));

Use the parameter to look up the value in the parameter list.

Sign up to request clarification or add additional context in comments.

1 Comment

@JonasWilms thank you very much! There is an extra bracket at the end, but it is exactly what I needed. I really appreciate it.
0

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})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.