0

This is my json object:

{
   id: 3,
   cno: 103,
   username: 'basha',
   name: 'New Complaint',
   desc: 'Need bag',
   storeId: [ 5, 1 ]
}

I want my expected output like this:

[
  {id: 3,cno: 103,username: 'basha',name: 'New Complaint',desc: 'Need bag',storeId:5},
  {id: 3,cno: 103,username: 'basha',name: 'New Complaint',desc: 'Need bag',storeId:1}
]
void
  • 36,090
  • 8
  • 62
  • 107
Mohamed Sameer
  • 2,998
  • 3
  • 22
  • 51

4 Answers4

4

You are right to choose .map. Issue is, you are trying to update an object and objects are passed using reference. So all the objects will hold same id. You will have to create a copy so that you do not override value. You can use Object.assign for that.

var data = {
   id: 3,
   cno: 103,
   username: 'basha',
   name: 'New Complaint',
   desc: 'Need bag',
   storeId: [ 5, 1 ]
};

var result = data.storeId.map(function(id){
  return Object.assign({}, data, {storeId: id});
});
console.log(result)

If you are not comfortable using ES6 features, you can check following: How do I correctly clone a JavaScript object?

Rajesh
  • 24,354
  • 5
  • 48
  • 79
1

You can use .map() on the array storeId and return a new object which has current value as the value of storeId.

var obj = {
   id: 3,
   cno: 103,
   username: 'basha',
   name: 'New Complaint',
   desc: 'Need bag',
   storeId: [ 5, 1 ]
};

var data = obj.storeId.map(el => {
  let newObject = Object.assign({}, obj);
  newObject.storeId = el;
  return newObject;
})

console.log(data);
void
  • 36,090
  • 8
  • 62
  • 107
1

You can use array#map with spread syntax to create an object with all the existing property and individual storeId.

var obj = {id: 3,cno: 103,username: 'basha',name: 'New Complaint',desc: 'Need bag',storeId: [ 5, 1 ]}
    result = obj.storeId.map(storeId => ({...obj, storeId}) )
console.log(result);
Hassan Imam
  • 21,956
  • 5
  • 41
  • 51
0

var data = {
   id: 3,
   cno: 103,
   username: 'basha',
   name: 'New Complaint',
   desc: 'Need bag',
   storeId: [ 5, 1 ]
}


var finalData = data.storeId.map(x => {
  return({
     id: data.id,
     cno: data.cno,
     username: data.username,
     name: data.name,
     desc: data.desc,
     storeId: x
  })
});

console.log(finalData);

I tried this now i got this answer correctly, is this good approach?

Mohamed Sameer
  • 2,998
  • 3
  • 22
  • 51
  • *is this good approach?* Yes. Since you are using ES6 features, you can check other answers suggesting `Object.assign`. – Rajesh Mar 01 '18 at 05:58
  • Yea definitely, nothing wrong here.. But you can get rid of the hassle of creating the whole object again by using `Object.assign()` and the suggested approach will be more robust in case certain object miss a key or gets a new key. – void Mar 01 '18 at 06:00