简体   繁体   English

有没有办法找到嵌套对象属性的兄弟值?

[英]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 )我想在不使用父项( obj.apple.description )的情况下通过名称找出appleorange的描述

Is there something like obj.apple.name.siblingProperty to get the value of description using name ?是否有类似obj.apple.name.siblingProperty的东西来使用name获取description的值?

You can loop through the object keys, find the index of name in that object, then get the next index to get description :您可以遍历 object 键,在 object 中找到name的索引,然后获取下一个索引以获取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.您应该在 object 上使用代理,在处理程序中只需使用 get function 即可。现在您可以做任何您想做的事情。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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