0

I have two arrays in an object named "customData". The arrays names are "headings" and "tabularData".
I want to modify "tabularData" array objects such that each object has properties matching first 6 properties of "headings" array and an "id" property in "tabularData".

sample "customData" object-

{
  headings: [{"id":"k1"},{"id":"k2"},...,{"id":"k6"}],
  tabularData: [{"k1":"v11","k2":"v12",...,"id":1},{"k1":"v21":"k2":"v22",...,"id":2}]
}

Expected result should be -

[{"k1":"v11","k2":"v12",...,"k6":"v16","id":1},
{"k1":"v21","k2":"v22",...,"k6":"v26","id":2}] 

My code-

let selectedHeadings = customData.headings.slice(0, 6);

let array = [];
let temp = {};
customData.tabularData.forEach((eachObj) => {
  for (const [key, value] of Object.entries(eachObj)) {
    if (
      selectedHeadings.find((heading) => heading.id === key) ||
      key === "id"
    ) {
      temp[key] = value;
      array.push(temp);
    }
  }
});
console.log(array);

sanbox link

Please help.

1 Answer 1

1

To start with, it makes things much easier if you turn your selected headings into a map

let selectedHeadings = customData.headings.slice(0, 6).reduce((acc, h) => {
  acc[h.id] = h;
  return acc;
}, {});

Beyond that, you were pushing to the new array inside the inner loop, not the outer loop. You should also start a new temp object inside each outer loop. This should do it:

let array = [];
customData.tabularData.forEach((eachObj) => {
  let temp = {};
  for (const [key, value] of Object.entries(eachObj)) {
    if (selectedHeadings[key] != undefined || key === "id") {
      temp[key] = selectedHeadings[key] || value;
    }
  }
  array.push(temp);
});

Forked Sandbox

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

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.