-2

I have the following data and tried the following, but I am unable to get the names of sub_values (like: Test1, Test5, Test10, Test20, Test50) either in [object Object] format or in json format and unable to show its length either (i.e 5, means we have sub_values names are five, so its length is 5).

var jsondata = [
{"id": "1","name": "test1","sub_values": [{"id": "1","name": "Test1","sub_values": []}]},
{"id": "2","name": "test2","sub_values": [{"id": "1","name": "Test5","sub_values": []},{"id": "1","name": "Test10","sub_values": []},{ "id": "1","name": "Test20","sub_values": []}]},
{"id": "3","name": "test3","sub_values": [{"id": "1","name": "Test50","sub_values": []}]}
];

console.log(jsondata);//(3) [Object, Object, Object] 
console.log(jsondata.sub_values.name);//Cannot read property 'name' of undefined 
console.log(jsondata.sub_values.length);//Cannot read property 'length' of undefined 

Error: Cannot read property 'name' of undefined

Cannot read property 'length' of undefined

Please let me know how to get this.

Created Fiddle.

Guna
  • 138
  • 4
  • 17
  • 1
    You will need to iterate through jsondata to get the values you want. Right now you're accessing properties on an array that don't exist. – Shadowfool Jun 20 '17 at 17:58
  • 1
    Take a look at this for iterating through the objects in the array, etc: https://jsfiddle.net/w2c3fgvh/1/ – Woodrow Jun 20 '17 at 18:03
  • @Woodrow, it is fine, thank you for your help. – Guna Jun 20 '17 at 18:23
  • If you only want to extract the sub-values one level deep, you can use `const fn1 = data => data.reduce((acc, val) => acc.concat(val.sub_values.map(elmt => elmt.name)), []);`. If you want to extract sub-values to any depth, you can modify this function to be recursive: `const fn2 = data => data.reduce((acc, val) => acc.concat(...val.sub_values.map(elmt => (elmt.sub_values.length === 0) ? elmt.name : [elmt.name, ...fn2([elmt])])), []);`. Try adding an extra layer of data, e.g. more sub_values under one of the currently-empty sub_values, to see the difference. – Andrew Willems Jun 20 '17 at 18:40

1 Answers1

2

As your jsondata is an array (or better pointing to an array) you should also mention the index for the same. So why don't you try this and let me know if this worked or not. See the code comments below.

console.log(jsondata[0]);//(3) Try this first
console.log(jsondata[0].sub_values[0].name);// Oh! You are onto something here.
console.log(jsondata[0].sub_values[0].length);// Now you realized you need to iterate an array!

How to iterate an array you ask ? Now that is entirely different question my friend!

d-coder
  • 12,813
  • 4
  • 26
  • 36