0
let devicesInfo = [
  { '96abc32b47fc10c88704b9a799c65b5c05455f4a9ef92013': '::1' },
  { '96abc32b47fc10c88704b9a799c65b5c05455f4a9ef92013': '::1' },
  { '96abc32b47fc10c88704b9a799c65b5c05455f4a9ef92013': '::1' }
  ]

let deviceId= "96abc32b47fc10c88704b9a799c65b5c05455f4a9ef92013"

I want check deviceId in deviceinfo array and get its value in result.

Mister Jojo
  • 20,093
  • 6
  • 21
  • 40
  • 1
    [Object.entries](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries) is probably what you ask for. But to be honest, I don't understand what your desired outcome ("check") would be. – A_A Oct 04 '20 at 13:51
  • Does this answer your question? [Array of objects check if it includes key value pair; on which position - Javascript](https://stackoverflow.com/questions/53971269/array-of-objects-check-if-it-includes-key-value-pair-on-which-position-javasc) – adzo261 Oct 04 '20 at 13:51
  • In your example, you have duplicate objects with the same key and value. If the key repeats will the value always be the same? If not, should it get the value of the first object or last object? Can you also please share your attempt? – Nick Parsons Oct 04 '20 at 13:54
  • what do you mean by "check key value pair" ? – Mister Jojo Oct 04 '20 at 14:01

2 Answers2

0

let devicesInfo = [
  { '96abc32b47fc10c88704b9a799c65b5c05455f4a9ef92013': '::1' },
  { '96abc32b47fc10c88704b9a799c65b5c05455f4a9ef92013': '::1' },
  { '96abc32b47fc10c88704b9a799c65b5c05455f4a9ef92013': '::1' }
];

let deviceId= "96abc32b47fc10c88704b9a799c65b5c05455f4a9ef92013";

let deviceValue = 'Device not found';

devicesInfo.forEach(device => {
  deviceValue = device[deviceId] ?? deviceValue;
});

console.log(deviceValue);
ElectricShadow
  • 683
  • 4
  • 16
0

let devicesInfo = [
  { '96abc32b47fc10c88704b9a799c65b5c05455f4a9ef92013': '::1' },
  { '96abc32b47fc10c88704b9a799c65b5c05455f4a9ef92013': '::1' },
  { '96abc32b47fc10c88704b9a799c65b5c05455f4a9ef92013': '::1' }
  ]

let deviceId= "96abc32b47fc10c88704b9a799c65b5c05455f4a9ef92013"

const getDevice = (id) => {
  devicesInfo.filter((val) => val.hasOwnProperty(id));
  return devicesInfo[0] ? devicesInfo[0][id] : undefined;
};

console.log(getDevice(deviceId)); // '::1'

console.log(getDevice('fhqwhgads')); // undefined
Trott
  • 66,479
  • 23
  • 173
  • 212