0

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];
 });
4
  • as I understood your question , you want to create an array of objects with the same property as the name property in the response object? Commented Jan 3, 2023 at 15:21
  • Array.prototype.filter() is all you need Commented Jan 3, 2023 at 15:24
  • Yes which I need to store in state Commented Jan 3, 2023 at 15:24
  • The callback of Array.prototype.map() is supposed to return something for every element in the array. Commented Jan 3, 2023 at 15:25

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

i have extended my question here with your reply :stackoverflow.com/questions/75003100/…
1

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

1 Comment

I have extended question here : stackoverflow.com/questions/75003100/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.