a=[{'report1':{'name':'Texas'}},{'report2':{'name':'Virginia'}}]
From the above javascript object I need to extract only 'report1' object. I can use foreach to iterate over 'a' but somehow need to extract 'report1' object.
The shortest way I can think of is using the .find() method:
var obj = a.find(o => o['report1']);
If there is no matching element in the array the result will be undefined. Note that .find() is an ES6 method, but there is a polyfill you can use for old browsers if you need it.
To get to the object that report1 refers to you can then say obj['report1'].
In context:
var a=[{'report1':{'name':'Texas'}},{'report2':{'name':'Virginia'}}];
var reportToFind = 'report1';
var obj = a.find(o => o[reportToFind]);
console.log(obj);
console.log(obj[reportToFind]); // {'name':'Texas'}
console.log(obj[reportToFind].name); // 'texas'
You could try using filter:
var report1 = a.filter(function(obj){ return obj['report1'] })[0]
report1 will be an object, or undefined
Introduced in ES5 probably supported by most new browsers.
See: http://kangax.github.io/compat-table/es5/#test-Array_methods_Array.prototype.filter
a.filter(obj => obj['report1'])...Here's one way to grab it:
var report1 = null;
for ( var i = 0, len = a.length; i < len; i++ )
{
if ( 'report1' in a[i] )
{
report1 = a[i].report1;
break;
}
}
Demo:
a=[{'report1':{'name':'Texas'}},{'report2':{'name':'Virginia'}}];
var report1 = null;
for ( var i = 0, len = a.length; i < len; i++ )
{
if ( 'report1' in a[i] )
{
report1 = a[i].report1;
break;
}
}
console.log('report1', report1);
You can use JSON.stringify(), JSON.parse(), String.prototype.replace()
var a = [{'report1':{'name':'Texas'}},{'report2':{'name':'Virginia'}}];
var res = JSON.parse(JSON.stringify(a, ["report1", "name"])
.replace(/,\{\}/, ""));
console.log(res)
res array contains only filtered object, given js at OP, and res[0] would provide the filtered object at index 0 of res array