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

592 views Asked by At

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?

2

There are 2 answers

0
Wais Kamal On BEST ANSWER

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

0
Saleh Majeed On

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