How to get a property value of an object which is located randomly

Viewed 44
res = {
  A: { device001: 1, device002: 2 },
  B: { device003: 3, device004: 4 }
};

For the above object in Javascript, I need to get the value of device001, however, device001 is exist but the position of device001 is unknown, for example:

res = {
  A: { device004: 4, device002: 2 },
  B: { device003: 3, device001: 1 }
};

please tell me how to get that value, thanks.

3 Answers

You could grab the values of your object using Object.values() and then use .find() to return the first value object which has "device001" as a key which you can check using the .hasOwnProperty() method. You can then use optional chaining to obtain the result from the object if it is found:

const obj = {
  A: { device001: 1, device002: 2 },
  B: { device003: 3, device004: 4 }
};

const search = "device001";
const result = Object.values(obj).find(obj => obj.hasOwnProperty(search))?.[search];
console.log(result);

If you can't support optional chaining yet, then you can check the truthiness of the result of using .find() first before trying to obtain the value from it:

const obj = {
  A: { device001: 1, device002: 2 },
  B: { device003: 3, device004: 4 }
};

const search = "device001";
const found = Object.values(obj).find(obj => obj.hasOwnProperty(search));
const result = found && found[search];
console.log(result);

You can iterate over the values of res using Object.values, and then, check if it has a property of the key you're looking for using Object.hasOwnProperty:

const res = {
  "A": { "device001": 1, "device002": 2 },
  "B": { "device003": 3, "device004": 4 }
};

const getValueInObject = (obj = {}, itemKey) => {
  for(const item of Object.values(obj))
    if(item.hasOwnProperty(itemKey))
      return item[itemKey];
  return;
}

console.log( getValueInObject(res, "device001") );
console.log( getValueInObject(res, "device004") );
console.log( getValueInObject(res, "") );

I support Nick answer. But for more clarity on the object type. I am giving you the explanation.

Object in JavaScript is like Dictionary with Key/Value pairs.

For the simple extracting of the property value, you can try the below code.

var res = {
    A: { device001: 1, device002: 2 },
    B: { device003: 3, device004: 4 }
  };
  
 
  console.log(res["A"]["device001"]); // output 1
  console.log(res["B"]["device001"]); // output undefined

undefined since the "device001" does not exist on B.

Related