1

Hello i have a state like this;

{
  "id": "8",
  "tablename": "demo_1",
  "segments": "segment_1"
},
{
  "id": "9",
  "tablename": "demo_2",
  "segments": "segment_2"
}

I want to take segments values from tablename. Like this:

this.state.MYSTATE.map[tablename:'demo_1'];

But ofc this wont work. Any help?

3
  • 2
    use findIndex for your array like this this.state.MYSTATE.findIndex(({tablename})=>tablename=='demo_1') Commented Oct 22, 2018 at 11:59
  • or .. this.state.MYSTATE.find((x)=> x.tablename =='demo_1') OR this.state.MYSTATE.find((x)=> x.tablename =='demo_1').tablename Commented Oct 22, 2018 at 12:02
  • @NarendraJadhav thanks thats work :) pls write this as an answer so i can mark. Commented Oct 22, 2018 at 12:22

2 Answers 2

1

You could use .findIndex() method for array.

The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1, indicating no element passed the test.

DEMO

const data =[{
    "id": "8",
    "tablename": "demo_1",
    "segments": "segment_1"
  },{
    "id": "9",
    "tablename": "demo_2",
    "segments": "segment_2"
  }];
  
let index = data.findIndex(({tablename})=>tablename=='demo_1');

console.log(index);
.as-console-wrapper {max-height: 100% !important;top: 0;}

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

Comments

1

what you need is a filter followed by a map

const data = [{
  "id": "8",
  "tablename": "demo_1",
  "segments": "segment_1"
},
{
  "id": "9",
  "tablename": "demo_2",
  "segments": "segment_2"
}]

const segments = data
  .filter(item => item.tablename === 'demo_1')
  .map(item => item.segments)
  
console.log(segments)

The filter will filter all the entry with tablename equal to demo_1 and map will return the segments values of these filtered results

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.