简体   繁体   中英

Is there a way to find the sibling value of a nested object's property?

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");

You should use proxy on your object and in the handler just use get function and that's it.now you can do whatever you want. here's my code

const obj = {
    apple: {
        name: 'Apple Juice',
        description: 'apple selected',
    },
    orange: {
        name: 'Orange Juice',
        description: 'orange selected',
    },
};

const handler = {
    get: function (target, prop, receiver) {
        return target[prop].description;
    },
};

const proxy = new Proxy(obj, handler);

console.log(proxy.apple);
console.log(proxy.orange);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM