Search code examples
javascriptarrayslodash

create array on basis of object's child


I am have array like:

[
  {
    "_id": "62434e4c52a870a3840f40fd",
    "Nome": [
      {
        "_id": "61f76c3c7a308dd136f1d33a",
        "value": "Oo",
        "updatedAt": "2022-05-04T00:00:00.000Z"
      }
    ],
    "Peso": [
      {
        "_id": "61f92ec87a308dd136c0e182",
        "value": "554",
        "updatedAt": "2022-05-04T00:00:00.000Z"
      }
    ],
    "createdAt": [
      {
        "value": "29/03/2022 03:22:02"
      }
    ]
  },
  {
    "_id": "62449de6ed196e40cb4309ae",
    "Nome": [
      {
        "_id": "61f76c3c7a308dd136f1d33a",
        "value": "Ssg",
        "updatedAt": "2022-05-04T00:00:00.000Z"
      }
    ],
    "Peso": [
      {
        "_id": "61f92ec87a308dd136c0e182",
        "value": "255",
        "updatedAt": "2022-05-04T00:00:00.000Z"
      }
    ],
    "createdAt": [
      {
        "value": "29/03/2022 03:23:26"
      }
    ]
  },
],

What I'm having trouble with is loop between each object example Nome, Peso the names of these arrays are dynamic and do not have a static name!

Example of what I'm thinking:

[
  {
    "_id": "62434e4c52a870a3840f40fd",
    "Nome": "Oo",
    "Peso": "554",
    "createdAt": "29/03/2022 03:22:02"
  },
  {
    "_id": "62449de6ed196e40cb4309ae",
    "Nome": "Ssg",
    "Peso": "255",
    "createdAt": "29/03/2022 03:23:26"
  }
],

Thanks for help :D


Solution

  • If considering those dynamic keys will have array then try below code.

    const data = [{
        "_id": "62434e4c52a870a3840f40fd",
        "Nome": [{
          "_id": "61f76c3c7a308dd136f1d33a",
          "value": "Oo",
          "updatedAt": "2022-05-04T00:00:00.000Z"
        }],
        "Peso": [{
          "_id": "61f92ec87a308dd136c0e182",
          "value": "554",
          "updatedAt": "2022-05-04T00:00:00.000Z"
        }],
        "createdAt": [{
          "value": "29/03/2022 03:22:02"
        }]
      },
      {
        "_id": "62449de6ed196e40cb4309ae",
        "Nome": [{
          "_id": "61f76c3c7a308dd136f1d33a",
          "value": "Ssg",
          "updatedAt": "2022-05-04T00:00:00.000Z"
        }],
        "Peso": [{
          "_id": "61f92ec87a308dd136c0e182",
          "value": "255",
          "updatedAt": "2022-05-04T00:00:00.000Z"
        }],
        "createdAt": [{
          "value": "29/03/2022 03:23:26"
        }]
      },
    ];
    
    data.map(d => {
      Object.keys(d).forEach(k => {
        if (Array.isArray(d[k]) && d[k].length > 0)
          d[k] = d[k][0].value;
      });
    });
    
    console.log(data);