Javascript: Changing the nested data structure

Yangwook Ian Jeong

I want to change a nested array, object to another structure, so I post a question.

// before
const beforeData = [
  { 
    product_id: 1,
    attribute_values: [
      { attribute_value_id: 1 },
      { attribute_value_id: 2 },
      { attribute_value_id: 3 }
    ]
  }, 
  { 
    product_id: 2,
    attribute_values: [
      { attribute_value_id: 1 },
      { attribute_value_id: 2 },
      { attribute_value_id: 3 }
    ]
  },

  (...)
];

// after
const afterData = [
  { product_id: 1, attribute_value_id: 1 },
  { product_id: 1, attribute_value_id: 2 },
  { product_id: 1, attribute_value_id: 3 },
  { product_id: 2, attribute_value_id: 1 },
  { product_id: 2, attribute_value_id: 2 },
  { product_id: 2, attribute_value_id: 3 },
];

I tried to create the data structure I wanted somehow using a library. But I did not get what I wanted and I got help from lodash. Note that attribute_values.length is exactly the same.

const getAttributeValueId = _.chain(beforeData[0].attribute_values)
  .flatten()
  .value();

console.log(getAttributeValueId)

On the console:

[ { attribute_value_id: 1 },
  { attribute_value_id: 2 },
  { attribute_value_id: 3 } ]
const getProductId = () => {
  const arrOne = [];
  data.forEach((val, idx) => {
    arrOne[idx] = { product_id: val.product_id };
  });

  const arrTwo = [];
  _.forEach(arrOne, (val, idx) => {
    for (let i = 0; i < getAttributeValueId.length; i++) {
      arrTwo.push(arrOne[idx]);
    }
  });
  return arrTwo;
};

console.log(getProductId());

On the console:

[ { product_id: 1 },
  { product_id: 1 },
  { product_id: 1 },
  { product_id: 2 },
  { product_id: 2 },
  { product_id: 2 },
  { product_id: 3 },
  { product_id: 3 },
  { product_id: 3 } ]

I do not know how I can insert attribute_value_id for each array anymore. I wanted to solve it by myself, but I do not have enough ability to solve it. I would appreciate your help.

And i have a question. Is it simpler than using for loop to solve by using array method likereduce, map?

Thanks for reading.

Nina Scholz

You could take (upcoming) Array#flatMap and map the common property to each nested properties.

const
    data = [{ product_id: 1, attribute_values: [{ attribute_value_id: 1 }, { attribute_value_id: 2 }, { attribute_value_id: 3 }] }, { product_id: 2, attribute_values: [{ attribute_value_id: 1 }, { attribute_value_id: 2 }, { attribute_value_id: 3 }] }],
    result = data.flatMap(({ product_id, attribute_values }) =>
        attribute_values.map(o => ({ product_id, ...o })));
    
console.log(result);

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related