0
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.

0

5 Answers 5

2

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'

Sign up to request clarification or add additional context in comments.

Comments

2

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

1 Comment

If you're going to use an arrow function, might as well go short: a.filter(obj => obj['report1'])...
1

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

Comments

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)

4 Comments

Why the downvote? It answers the question, in a unique and interesting way.
What is purpose of "downvote" without description where expected result is returned?
I didn't vote this down, but note that it doesn't return the object, it returns an array containing the object.
@nnnnnn Yes, you are technically correct, though gist of expected result is returned at stacksnippets; i.e.g.; res array contains only filtered object, given js at OP, and res[0] would provide the filtered object at index 0 of res array
0
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);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.