Home > front end >  If object set has an object property create an array
If object set has an object property create an array

Time:01-04

I have a response value which is dynamic which i need to store in redux state,

Response consist of array of object and and name ex :

{data:[
 {name:"abc",age:"10",id:"10"}
 {name:"abc",age:"15",id:"20"}
 {name:"def",age:"15",id:"20"}
 ]
 name: "abc"
}

So if the name is same I need to create array with the name.

Expected :

abc:[
   {name:"abc",age:"10",id:"10"}
   {name:"abc",age:"15",id:"20"}
]

something I tried

data.map(function(o) {
       if(data.name ==o.name)
        return name[o];
 });

CodePudding user response:

If you're wanting a new object with a key of the name property you could try something like this

const response = {
  data: [{
      name: "abc",
      age: "10",
      id: "10"
    },
    {
      name: "abc",
      age: "15",
      id: "20"
    },
    {
      name: "def",
      age: "15",
      id: "20"
    },
  ],
  name: "abc"
}

const createSet = (someData) => {
  let key = someData.name
  let data = someData.data.filter(e => e.name === key)
  return {
    [key]: data
  }
}

console.log(createSet(response))

CodePudding user response:

You can extract duplicated using reduce and filter :

var data = {
data:[
 {name:"abc",age:"10",id:"10"},
 {name:"abc",age:"15",id:"20"},
 {name:"def",age:"15",id:"20"}
 ],
 name: "abc"
}

const lookup = data.data.reduce((a, e) => {
  a[e.name] =   a[e.name] || 0;
  return a;
}, {});

console.log(data.data.filter(e => lookup[e.name]));

  • Related