0

I have an object of arrays, I want to create individual objects from those array values,

"SUMMARY_TABLE": {
                "PRODUCT_CODE": [
                    123,
                    123,
                    123,
                    123,
                    123
                ],
                "TYPE": [
                    "CURRENT",
                    "OPTIMAL",
                    "MINIMUM",
                    "MAXIMUM",
                    "FUTURE"
                ],
                "LOT_SIZE": [
                    268.0,
                    268.0,
                    268.0,
                    268.0,
                    500.0
                ]}

above is the response Im getting. I want to create 5 individual objects from this data like

{
"product_code": 123,
"type": "current",
"lot_size" : 268
}

similarly using values in the arrays at other indexes. I am trying this but it is not giving me the result I need. k contains the key name and array of values, like ['Product_Code', Arr(5)]

const data = Object.entries(selectedProductDetails.SUMMARY_TABLE).map(
    (k, v) => {
      let obj = {};
      return {
        ...obj, k: k[i++]
      }
    });

I would appreciate any help in this.

2 Answers 2

1

You can use .map and create a new object for each element.

Here's an example:

const summaryTable = {
  "PRODUCT_CODE": [
      123,
      123,
      123,
      123,
      123
  ],
  "TYPE": [
      "CURRENT",
      "OPTIMAL",
      "MINIMUM",
      "MAXIMUM",
      "FUTURE"
  ],
  "LOT_SIZE": [
      268.0,
      268.0,
      268.0,
      268.0,
      500.0
  ]
};

const individualObjects = summaryTable.PRODUCT_CODE.map((productCode, index) => {
  return {
    product_code: productCode,
    type: summaryTable.TYPE[index].toLowerCase(),
    lot_size: summaryTable.LOT_SIZE[index]
  }
});

console.log(individualObjects);
Sign up to request clarification or add additional context in comments.

1 Comment

thanks a lot! this was very simple to follow
1

You can iterate over all the values of one of the arrays stored in table to be able to get the index, then iterate over the keys & values of table to get every property. This makes it so if table changes, you don't need to modify this code.

const table = {
  PRODUCT_CODE: [123, 123, 123, 123, 123],
  TYPE: ["CURRENT", "OPTIMAL", "MINIMUM", "MAXIMUM", "FUTURE"],
  LOT_SIZE: [268.0, 268.0, 268.0, 268.0, 500.0],
};

const entries = Object.entries(table);
const data = table.TYPE.map((_, i) => entries.reduce((acc, [key, value]) => {
  acc[key] = value[i];
  if (key === "TYPE") acc[key] = value[i].toLowerCase(); // if you need this, keep it
  return acc;
}, {}));

console.log(data);

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.