Dimas Rizqi
Dimas Rizqi

Reputation: 85

How to convert array to object in an array of objects

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?

Upvotes: 1

Views: 162

Answers (4)

Robin Webb
Robin Webb

Reputation: 1521

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
  }))
})));

Upvotes: 0

Oskar Hane
Oskar Hane

Reputation: 1884

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}
}, [])

Upvotes: 1

Jinu Joseph Daniel
Jinu Joseph Daniel

Reputation: 6291

It is as simple as

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

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337560

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);

Upvotes: 4

Related Questions