Resolved: How to get all the values of a property name in an object?

Question:

I have an object and I want to build up a function, take the object and a property name and the function returns the value of that property, if you see that you gonna say, “Oh it’s so easy, just use a double quotation or dot notation to access that value” BUT I want the function to return me not only the first level property value, But also their nested if there’s any object inside that object and search for that propertyName if exists accumulate the value in the array, and return the result:
let obj = {
  a: {
    b: "value of b",
  },
  b: "another value of b",
  c: {
    d: [1, 2, 3],
  },
};
//                        input    output
getDeepValuesProperty(obj, "a"); //{ b: "value of b" }
getDeepValuesProperty(obj, "b"); //["value of b", "another value of b"]
getDeepValuesProperty(obj, "d"); //[1, 2, 3]

let obj = {
  a: {
    b: "value of b",
  },
  b: "another value of b",
  c: {
    d: [1, 2, 3],
  },
};

function getDeepValuesProperty(object, propertyName) {
  if (object[propertyName]) {
    return object[propertyName];
  } else if (typeof object[propertyName] == "object") {
    return getDeepValuesProperty(object[propertyName], propertyName);
  }
}
console.log(getDeepValuesProperty(obj, "a")); //{ b: "value of b" }
console.log(getDeepValuesProperty(obj, "b")); //another value of b
console.log(getDeepValuesProperty(obj, "d")); //undefined

The first example worked, but the second doesn’t work as I expect and return just the last value, the third example return undefined I don’t know why this happens, do I miss anything in the recursion function?

Answer:

Your getDeepValuesProperty() function instantly return your object value if one of if your statements match. If you need all the occurrences, you need to aggregate these results, using a .reduce function for example.
let obj = {
  a: {
    b: "value of b",
  },
  b: "another value of b",
  c: {
    d: [1, 2, 3],
  },
};

function getDeepValuesProperty(object, propertyName) {
    return Object.entries(object).reduce((values, [key, value]) => {
        if (key === propertyName) {
            return [...values, value];
        } else if (typeof value === 'object') {
            return [...values, ...getDeepValuesProperty(value, propertyName)];
        }
        return values;
    }, []);
}

console.log(getDeepValuesProperty(obj, 'a')); // [ { b: 'value of b' } ]
console.log(getDeepValuesProperty(obj, 'b')); // [ 'value of b', 'another value of b' ]
console.log(getDeepValuesProperty(obj, 'd')); // [ [ 1, 2, 3 ] ]

If you have better answer, please add a comment about this, thank you!

If you like this answer, you can give me a coffee by <a href=”https://violencegloss.com/mkw7pgdwwr?key=2a96ade6f3760c7e63343a320febb78e”>click here</a>

Source: Stackoverflow.com