Home > Blockchain >  Javascript Object move object key into value array
Javascript Object move object key into value array

Time:04-04

how can I transfer a key to a value which is an object. I would like to move key which is the product ID level down to a value as "id"

I have an array like this:

const products = [
  {
    "2": {
      "name": "Name of product with id 2",
      "ean": "123123123",
      "parameters": []
      },
    "3": {
      "name": "Name of product with id 3",
      "ean": "123123122",
      "parameters": []
      },
    "5": {
      "name": "Name of product with id 5",
      "ean": "123123121",
      "parameters": []
      }
  }
]

I am expecting this:

[
  {
    "id": "2",
    "name": "Name of product with id 2",
    "ean": "123123123",
    "parameters": []
  },
  {
    "id": "3",
    "name": "Name of product with id 3",
    "ean": "123123122",
    "parameters": []
  },
  {
    "id": "5",
    "name": "Name of product with id 5",
    "ean": "123123121",
    "parameters": []
  }
]

CodePudding user response:

const products = [
  {
    "2": { "name": "Name of product with id 2", "ean": "123123123", "parameters": [] },
    "3": { "name": "Name of product with id 3", "ean": "123123122", "parameters": [] },
    "5": { "name": "Name of product with id 5", "ean": "123123121", "parameters": [] }
  }
];

const res = products
  .flatMap(Object.entries)
  .map(([ id, props ]) => ({ ...props, id }));

console.log(res);

CodePudding user response:

You can simply achieve that by using Object.keys() along with Array.map() method.

Demo :

const products = [
  {
    "2": {
      "name": "Name of product with id 2",
      "ean": "123123123",
      "parameters": []
      },
    "3": {
      "name": "Name of product with id 3",
      "ean": "123123122",
      "parameters": []
      },
    "5": {
      "name": "Name of product with id 5",
      "ean": "123123121",
      "parameters": []
      }
  }
];

const res = Object.keys(products[0]).map((id) => {
    products[0][id]['id'] = id;
  return products[0][id];
});

console.log(res);

  • Related