javascript - Access / process (nested) objects, arrays or JSON -
javascript - Access / process (nested) objects, arrays or JSON -
i have (nested) info construction containing objects , arrays. how can extract information, i.e. access specific or multiple values (or keys)?
for example:
var info = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] };
how access name
of sec item in items
?
preliminaries
javascript has 1 info type can contain multiple values: object. array special form of object.
(plain) objects have form
{key: value, key: value, ...}
arrays have form
[value, value, ...]
both arrays , objects expose key -> value
structure. keys in array must numeric, whereas string can used key in objects. key-value pairs called "properties".
properties can accessed either using dot notation
var value = obj.someproperty;
or bracket notation, if property name not valid javascript identifier name [spec], or name value of variable:
// space not valid character in identifier names var value = obj["some property"]; // property name variable var name = "some property"; var value = obj[name];
for reason, array elements can accessed using bracket notation:
var value = arr[5]; // arr.5 syntax error // property name / index variable var x = 5; var value = arr[x];
wait... json? json textual representation of data, xml, yaml, csv, , others. work such data, first has converted javascript info types, i.e. arrays , objects (and how work explained). how parse json explained in question parse json in javascript? .
accessing nested info structuresa nested info construction array or object refers other arrays or objects, i.e. values arrays or objects. such structures can accessed consecutively applying dot or bracket notation.
here example:
var info = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] };
let's assume want access name
of sec item.
here how can step-by-step:
as can see data
object, hence can access properties using dot notation. items
property accessed follows:
data.items
the value array, access sec element, have utilize bracket notation:
data.items[1]
this value object , utilize dot notation 1 time again access name
property. get:
var item_name = data.items[1].name;
alternatively, have used bracket notation of properties, if name contained characters have made invalid dot notation usage:
var item_name = data['items'][1]['name'];
i'm trying access property undefined
back? most of time when getting undefined
, object/array doesn't have property name.
var foo = {bar: {baz: 42}}; console.log(foo.baz); // undefined
use console.log
or console.dir
, inspect construction of object / array. property trying access might defined on nested object / array.
console.log(foo.bar.baz); // 42
what if property names dynamic , don't know them beforehand? if property names unknown or want access properties of object / elements of array, can utilize for...in
[mdn] loop objects , for
[mdn] loop arrays iterate on properties / elements.
to iterate on properties of data
, can iterate on object so:
for(var prop in data) { // `prop` contains name of each property, i.e. `'code'` or `'items'` // consequently, `data[prop]` refers value of each property, i.e. // either `42` or array }
depending on object comes (and want do), might have test in each iteration whether property property of object, or inherited property. can object#hasownproperty
[mdn].
to iterate on elements of data.items
array, utilize for
loop:
for(var = 0, l = data.items.length; < l; i++) { // `i` take on values `0`, `1`, `2`,..., i.e. in each iteration // can access next element in array `data.items[i]`, example: // // var obj = data.items[i]; // // since each element object (in our example), // can access objects properties `obj.id` , `obj.name`. // utilize `data.items[i].id`. }
one utilize for...in
iterate on arrays, there reasons why should avoided: why 'for(var item in list)' arrays considered bad practice in javascript?.
with increasing browser back upwards of ecmascript 5, array method foreach
[mdn] becomes interesting alternative well:
data.items.foreach(function(value, index, array) { // callback executed each element in array. // `value` element (equivalent `array[index]`) // `index` index of element in array // `array` reference array (i.e. `data.items` in case) });
what if "depth" of info construction unknown me? in add-on unknown keys, "depth" of info construction (i.e. how many nested objects per array) has, might unknown well. how access nested properties depends on exact info structure, then?
if info construction contains repeating structures, e.g. representation of binary tree, solution typically includes recursively [wikipedia] access each level of info structure.
here illustration first leaf node of binary tree:
function getleaf(node) { if (node.leftchild) { homecoming getleaf(node.leftchild); // <- recursive phone call } else if (node.rightchild) { homecoming getleaf(node.rightchild); // <- recursive phone call } else { // node must leaf node homecoming node; } } var first_leaf = getleaf(root);
class="snippet-code-js lang-js prettyprint-override">var root = { leftchild: { leftchild: { leftchild: null, rightchild: null, data: 42 }, rightchild: { leftchild: null, rightchild: null, data: 5 } }, rightchild: { leftchild: { leftchild: null, rightchild: null, data: 6 }, rightchild: { leftchild: null, rightchild: null, data: 7 } } }; function getleaf(node) { if (node.leftchild) { homecoming getleaf(node.leftchild); } else if (node.rightchild) { homecoming getleaf(node.rightchild); } else { // node must leaf node homecoming node; } } alert(getleaf(root).data);
a more generic way access nested info construction unknown keys , depth test type of value , deed accordingly.
here illustration adds primitive values within nested info construction array (assuming not contain functions). if encounter object (or array) phone call toarray
1 time again on value (recursive call).
function toarray(obj) { var result = []; (var prop in obj) { var value = obj[prop]; if (typeof value === 'object') { result.push(toarray(value)); // <- recursive phone call } else { result.push(value); } } homecoming result; }
class="snippet-code-js lang-js prettyprint-override">var info = { code: 42, items: [{ id: 1, name: 'foo' }, { id: 2, name: 'bar' }] }; function toarray(obj) { var result = []; (var prop in obj) { var value = obj[prop]; if (typeof value === 'object') { result.push(toarray(value)); } else { result.push(value); } } homecoming result; } alert(json.stringify(toarray(data)));
since construction of complex object or array not obvious, can inspect value @ each step decide how move further. console.log
[mdn] , console.dir
[mdn] help doing this. illustration (output of chrome console):
> console.log(data.items) [ object, object ]
here see that data.items
array 2 elements both objects. in chrome console objects can expanded , inspected immediately.
> console.log(data.items[1]) object id: 2 name: "bar" __proto__: object
this tells data.items[1]
object, , after expanding see has 3 properties, id
, name
, __proto__
. latter internal property used prototype chain of object. prototype chain , inheritance out of scope answer, though.
how access arrays , objects basic javascript knowledge , hence advisable read mdn javascript guide, sections
working objects arrays javascript arrays object recursion
Comments
Post a Comment