Home > Software engineering >  return a value of array that have special name
return a value of array that have special name

Time:08-15

Im new in react js and I get a problem with my array... I want to return a value of my array that have contain name and adress .and all value are string thi is my data that I need name :123, adress:12569

const array = [
  0: [ 'name','123' ],
  1: [ 'adress','12569'],
  2: ['family','4'],
];

CodePudding user response:

You can run loop on the array and assign key-value for each of the array items.

const array = [
  ['name', '123'],
  ['adress', '12569'],
  ['family', '4'],
];
const res = {};
array.forEach((item) => {
  res[item[0]] = item[1];
})

console.log(res);

CodePudding user response:

In this case, you should use an Object.

const foo = {
    name: '123',
    adress: 'bar',
    family: '4',
}

So, to access the propertys:

console.log(foo.name); // 123
console.log(foo.adress); // bar
console.log(foo.family); // 4

But if you are getting this information as an array, you can always transform it into an object.

CodePudding user response:

It would make more sense for that data to be combined into a single object rather than a series of nested arrays, and then use find to locate the object that matches the query.

const data = [
  { name: 'Bob', address: '999 Letsbe Avenue', family: 4 },
  { name: 'Sally', address: '8 Treehouse Lane', family: 0 },
  { name: 'Joan', address: '85 Long Terrace', family: 6 }
];

// Accepts the data array, and a query object
function findFamily(data, query) {

  // Iterate through the data array to `find`
  return data.find(obj => {

    // Split the query into key/value pairs
    const queryEntries = Object.entries(query);

    // And return only those objects where the
    // object key/value matches the query key/value
    return queryEntries.every(([ key, value ]) => {
      return obj[key] === value;
    });

  // And if there are no matches return 'No match'
  }) || 'No match';
}

console.log(findFamily(data, {
 name: 'Bob',
 address: '999 Letsbe Avenue',
 family: 0
}));

console.log(findFamily(data, {
 address: '999 Letsbe Avenue',
 family: 4
}));

console.log(findFamily(data, {
 name: 'Sally'
}));

Additional documentation

  • Related