Recreate array on basis of object's child

Viewed 85

Some time ago I asked a question about how to filter array based on its key today this function but i am working a new implementation that I'm doing.

create array on basis of object's child

But I'm doing a refactoring of how I treat the field value because before I just need the first object and its value [0].value now I need to expand this logic to work with array I'll leave some examples below.

My Code I'm currently using https://codesandbox.io/s/lodash-tester-forked-fcdmy1?file=/index.js

Original, unfiltered data from API:

[
  {
    "_id" : ObjectId("62548802054c225fe560f41a"),
    "test" : [ 
      "taetea", 
      "atty", 
    ],
    "Peso" : [ 
      {
        "_id" : "624f2ab363dd92f2101de167",
        "value" : "255"
      }
    ],
  }
]

Expected result for table data:

[
  {
    "_id" : "62548802054c225fe560f41a",
    "test1":"taetea",
    "test2":"atty",
    "Peso":"255"
  },
  {
  ...
  },
]

Anyone who can help I'm grateful I will repay with rep+ and my eternal thanks xD

1 Answers

As i understand,you want to use title property from the table Columns & search it in the API data.If the title property represents an array of strings,then add all the strings otherwise add the value property.

const apiData =  [
  {
    "_id" : "62548802054c225fe560f41a",
    "test" : [ 
      "taetea", 
      "atty", 
    ],
    "Peso" : [ 
      {
        "_id" : "624f2ab363dd92f2101de167",
        "value" : "255"
      }
    ],
  }
];

const tableData = [
  {
    title: "Peso",
    dataIndex: "peso",
    key: "peso",
  },
  {
    title: "test",
    children: [
      {
        title: "ex: ${title} field ${title.length}",
        dataIndex: "ex: ${title} + ${title.length}",
        key: "ex: ${title} + ${title.length}",
      },
      {
        title: "ex: ${title} field ${title.length}",
        dataIndex: "ex: ${title} + ${title.length}",
        key: "ex: ${title} + ${title.length}",
      },
    ],
  },
];

const tableKeys = tableData.map(t => t.title)
const output = []
apiData.forEach(obj => {
const data = []
 Object.keys(obj).filter(key =>  tableKeys.includes(key)).forEach(key =>{
   if(typeof obj[key][0]=== 'string'){
      data.push(...obj[key].map((val,index) => ({[`${key}${index+1}`]:val})))
  }else{
      data.push({[key]: obj[key][0].value})
  }
  
 })
 // Add the id of the the api data & spread the objects collected
 output.push({'_id':obj._id,
              ...data.reduce((map,elem)=>({...map,...elem}),
                             {})})
})
console.log('output',output)

Related