3

I have props with following data

test1: abc
id: 1
myArray: Array(3)
0: {a:abc, b:cde, aid: 1}
1: {e:age, f:ade, aid: 2}
2: {t:are, h:had, aid: 1}

I want to filter props and update array to have only the values that match id and aid

So the props should look like below:

test1: abc
id: 1
myArray: Array(3)
0: {a:abc, b:cde, aid: 1}
2: {t:are, h:had, aid: 1}

How can i do that?

1
  • I was gonna post a filter implementation but there is one detail, props are inmutable... is that correct? you want to change the props of the current component? Commented Jun 4, 2018 at 0:03

3 Answers 3

2

You can use the filter Array method

let myArray = [{a:"abc", b:"cde", aid: 1},
               {e:"age", f:"ade", aid: 2},
               {t:"are", h:"had", aid: 1}]

const result = myArray.filter(item => item.aid === 1)

console.log(result)

But take in consideration that props are immutable.

If you wish to change this prop permanently you will have to update it in the parent component.

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

Comments

1

You will get the filtered data by using,

const filteredData = this.props.myArray.filter(item => item.aid === 1)

However props is only readable. You will have to eigther dispatch or update parent component to provide new/filtered data as props.

2 Comments

I am new to React. Could useState be used to update the state according the filtered list? Say, if I'm filtering 3 lists out of the prop variable, should I have 3 separate states? Thanks!
Found it! Filtering and creating new variables out of props should involve useStates that are called upon useEffects.
0

you can use Array.filter()

// match both a AND aid
const result = myArray.filter(obj => (obj.a === test1 && obj.aid === id);
// match either a OR aid
const result = myArray.filter(obj => (obj.a === test1 || obj.aid === id);

Comments

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.