Home > Enterprise >  How to convert array to object in an array of objects
How to convert array to object in an array of objects

Time:10-11

I have this sample data

let data = [{
    id: 1,
    info: [
      'Optical',
      'Drive'
    ]
  },
  {
    id: 2,
    info: [
      'Paper',
      'Binder'
    ]
  }
];

I want to convert the array in data.info to object and assign 2 key/value pairs, first key is name with value from data.info and 2nd key is the length of data.info string. The result would be something like this:

let data = [{
    id: 1,
    info: [{
        name: 'Optical',
        length: 7
      },
      {
        name: 'Drive',
        length: 5
      },
    ]
  },
  {
    id: 2,
    info: [{
        name: 'Paper',
        length: 5
      },
      {
        name: 'Binder',
        length: 6
      }
    ]
  }
];

Here's what I've tried so far

const getLength = (str) => (str.length)

const addLength = (str) => {
  try {
    let newObj = {};
    newObj.name = str;
    newObj.length = getLength(str);
    return newObj;
  } catch (error) {
    console.log(error)
  }
}

const mapedData = data.map((object) => {
  object.info.map((str) => (addLength(str)))
})

However the result is

[ undefined, undefined ]

Any idea how to fix it?

CodePudding user response:

To do what you require you can loop through the array, using map() to update the info array within each element. The part your original logic is missing is that you don't set the response of addLength() to the property of the parent object - you just execute the function.

let data = [{id: 1,info: ['Optical','Drive']}, {id: 2,info: ['Paper','Binder']}];

data.forEach(x => {
  x.info = x.info.map(y => ({
    name: y,
    length: y.length
  }))
});

console.log(data);

CodePudding user response:

It is as simple as

data.forEach(item => item.info = item.info.map((value) => ({name: value, length: value.length})));

CodePudding user response:

This should do it.

const result = data.map(curr => {
  // Calculate new info array
  const info = curr.info.map(item => ({name: item, length: item.length}))
  // Create new object from old object and use the new info
  // to not mutate the original object
  return {...curr, info}
}, [])

CodePudding user response:

const data = [{
    id: 1,
    info: [
      'Optical',
      'Drive'
    ]
  },
  {
    id: 2,
    info: [
      'Paper',
      'Binder'
    ]
  }
];

console.log(data.map(e => ({
  id: e.id,
  info: e.info.map(i => ({
    name: i,
    length: i.length
  }))
})));

  • Related