user1050619
user1050619

Reputation: 20856

javascript find object name in an array

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.

Upvotes: 0

Views: 12637

Answers (5)

Restu Adi
Restu Adi

Reputation: 26

var a=[{'report1':{'name':'Texas'}},{'report2':{'name':'Virginia'}}]
for(var report in a){
 var reportRow = a[report];
 if(reportRow['report1']){
 var report1Extract = reportRow;
 }
}
console.log(report1Extract);

Upvotes: 0

jmunsch
jmunsch

Reputation: 24089

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

Upvotes: 2

nnnnnn
nnnnnn

Reputation: 150020

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'

Upvotes: 2

guest271314
guest271314

Reputation: 1

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)

Upvotes: 1

Blue
Blue

Reputation: 22911

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);

Upvotes: 1

Related Questions