1

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?

pr -
  • 240
  • 2
  • 9
  • 2
    Please elaborate on your problem. I don't quite understand what you are asking for. – Felix Kling May 26 '21 at 19:10
  • No, because that would be unreliable. The ordering of properties follows specified rules, but you can't do anything about the rules, so depending on the ordering would make for extremely fragile code. – Pointy May 26 '21 at 19:12
  • 1
    It will help if you would explain *why* `obj.apple.description` is undesirable. – Pointy May 26 '21 at 19:13
  • 2
    There is nothing like that. You could write a helper function to iterate the properties of `obj.apple`, but any solution will be worse than just doing `obj.apple.description`. – Felix Kling May 26 '21 at 19:15

2 Answers2

1

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");
Wais Kamal
  • 5,858
  • 2
  • 17
  • 36
0

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);
Saleh Majeed
  • 19
  • 1
  • 4