Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the key value from nested object

I am having below object where I am trying to get all the id values.

[{
    "type": "test",
    "id": "100",
    "values": {
        "name": "Alpha"
    },
    "validations": []
}, {
    "type": "services",
    "validations": [{
        "id": "200",
        "name": "John",
        "selection": [{
            "id": "300",
            "values": {
                "name": "Blob"
            }
        }]
    }]
}]

Using the below code, I am getting only the first id value. Is there any way to get all the id values from the nested object without using any external module.

for (var prop in obj) {
            console.log(prop)
            if (prop === key) {
                set.push(prop);
            }
        }

Expected Output

[100,200,300]     //all id values
like image 479
user4324324 Avatar asked Mar 03 '26 08:03

user4324324


2 Answers

You can use a JavaScript function like below to get the nested properties:

function findProp(obj, key, out) {
    var i,
        proto = Object.prototype,
        ts = proto.toString,
        hasOwn = proto.hasOwnProperty.bind(obj);

    if ('[object Array]' !== ts.call(out)) out = [];

    for (i in obj) {
        if (hasOwn(i)) {
            if (i === key) {
                out.push(obj[i]);
            } else if ('[object Array]' === ts.call(obj[i]) || '[object Object]' === ts.call(obj[i])) {
                findProp(obj[i], key, out);
            }
        }
    }

    return out;
}

Check this Fiddle for a working solution.

like image 172
Hector Barbossa Avatar answered Mar 05 '26 21:03

Hector Barbossa


Using Object.keys

function findProp(obj, prop) {
  var result = [];
  function recursivelyFindProp(o, keyToBeFound) {
    Object.keys(o).forEach(function (key) {
      if (typeof o[key] === 'object') {
        recursivelyFindProp(o[key], keyToBeFound);
      } else {
        if (key === keyToBeFound) result.push(o[key]);
      }
    });
  }
  recursivelyFindProp(obj, prop);
  return result;
}


// Testing:
var arr = [{
    "type": "test",
    "id": "100",
    "values": {
        "name": "Alpha"
    },
    "validations": []
}, {
    "type": "services",
    "validations": [{
        "id": "200",
        "name": "John",
        "selection": [{
            "id": "300",
            "values": {
                "name": "Blob"
            }
        }]
    }]
}];

console.log(findProp(arr, "id"));
like image 38
Adriano P Avatar answered Mar 05 '26 20:03

Adriano P



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!