Vicheanak Vicheanak - 4 months ago 19
Javascript Question

How to Flatten Object Underscore with a new Property?

I'm having an array of this:

var arr = [
{
name: 'John',
age: {
id: 1,
value: 'less than 19'
}
},
{
name: 'Doe',
age: {
id: 2,
value: 'more than 19'
}
}
]


How can I use underscore to flatten the age object in the array. The expected result is:

arr == [
{
name: 'John',
age: 'less than 19'
},
{
name: 'Doe',
age: 'more than 19'
}
];


Thanks,

Answer

You can try this:

var result = arr.map(function(item) {
    return {
        name: item.name,
        age: item.age.value
    };
});

Demo:

var arr = [{
  name: 'John',
  age: {
    id: 1,
    value: 'less than 19'
  }
}, {
  name: 'Doe',
  age: {
    id: 2,
    value: 'more than 19'
  }
}];

var result = arr.map(function(item) {
  return {
    name: item.name,
    age: item.age.value
  };
});

console.log(result);

I hope this will help you.

Comments