Here's my structure:
var obj = {
apple: {
name: "Apple Juice",
description: "",
},
orange: {
name: "Orange Juice",
description: "",
}
}
I want to find out the description of apple
or orange
by its name without using the parent (obj.apple.description
)
Is there something like obj.apple.name.siblingProperty
to get the value of description
using name
?
You can loop through the object keys, find the index of name
in that object, then get the next index to get description
:
var obj = {
apple: {
name: "Apple Juice",
description: "",
},
orange: {
name: "Orange Juice",
description: "",
}
}
function getNextKey(object, key) {
var keys = Object.keys(object);
var keyIndex = keys.indexOf(key);
var nextKey = keys[keyIndex + 1];
console.log(nextKey + ": " + object[nextKey]);
}
getNextKey(obj.apple, "name");
getNextKey(obj.orange, "name");