Home > OS >  How to find names by id
How to find names by id

Time:06-01

Find Names by ids i have two arrays want to find names by their ids.

person: [
  {id: 1, name: 'abc'},
  {id: 2, name: 'xyz'},
  {id: 3, name: 'pqr'},
  ]

data: [
  {id: 1, personId: [1,2,3]},
  {id: 2, personId: [1,3]},
  {id: 3, personId: [1,2]},
]

Expected Output:

personId: [1,2,3] return // abc,xyz,pqr
personId: [1,3] return // abc,pqr
personId: [1,2] return // abc,xyz

I am using react-native.

I have tried this:

for (let person of this.state.data) {
  for (let personName of person['personId']){
    let name = this.state.person.find(nme => nme['id'] === personName);
    alert(name);
  }  
}

Any help would be greatly appreciated

CodePudding user response:

You can use find

result = []
for (let i=0; i < personId.length; i  ) {
    result.push(person.find(data => data.id === personId[i]).name);
}

in order to be able to retrieve objects in your person array based on the id.

CodePudding user response:

I guess that's JSON data stringify-ied or a JSON in general. So, you can first parse it to JS object to make it easier for you to use JS. But let me leave that part to you. I changed your data to array so that I can directly show you what I would do if it helps. It's good to use methods that don't mutate original data. So I used array methods slice, forEach and map in this case. This way you can safely create a new data that is a replica of data (var data) but by including new property 'personNames', which is mapped from the other variable (person).

const person = [
  {id: 1, name: 'abc'},
  {id: 2, name: 'xyz'},
  {id: 3, name: 'pqr'},
];
const data = [
  {id: 1, personId: [1,2,3]},
  {id: 2, personId: [1,3]},
  {id: 3, personId: [1,2]},
];

// not to mutate your original data, just in case
const dataWithNames = data.slice();
// console.log(dataWithNames);

// modifying new data to include personNames property
dataWithNames.forEach( eachData => {
  // let eachIdP = eachData.personId;
  // creating new array by mapping person id to names from person data
  let mappedNames = eachData.personId.map( pID => {
      // goes to refer person data with same id
      person.forEach( eachPerson => {
         if ( eachPerson.id === pID ) {
              pID = eachPerson.name;
         }
      } );
      return pID;
  } );
  // console.log(mappedNames);

  // adding new property 'personNames' and 
  // assign them to respective mappedNames
  eachData.personNames = mappedNames;
} );
// console.log(dataWithNames);

This will get you the following.

/*
[
 {
  id: 1,
  personId: [ 1, 2, 3 ],
  personNames: [ 'abc', 'xyz', 'pqr' ]
 },
 { id: 2, personId: [ 1, 3 ], personNames: [ 'abc', 'pqr' ] },
 { id: 3, personId: [ 1, 2 ], personNames: [ 'abc', 'xyz' ] }
]*/

I hope this will help you.

  • Related