0

I'm looking at extracting keys from an Object and push them to an array in Javascript (Nodejs). An example would be:

var obj = [{tag: 'ft001', addr: 'DB415.DBD2'}, {tag: 'ft001', addr: 'DB415.DBD6'}];

function extractKey(arr, keyName) { 

// Result: ['ft001', 'ft002'];

}

How would I go about doing this?

RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105
adalal
  • 105
  • 2
  • 9

2 Answers2

1

if a typo [ 'ft001', 'ft002'], then the following would you be useful:

function extractKey() {
    var result = [];
    for (var index = 0; index < obj.length; index++) {
        result.push(obj[index].tag);        
    }
    return result;
// Result: ['ft001', 'ft001'];
}
1

Use Array.prototype.map():

var obj = [{tag: 'ft001', addr: 'DB415.DBD2'}, {tag: 'ft001', addr: 'DB415.DBD6'}];

function extractKey(arr, keyName) { 
  return arr.map(x=> x[keyName])
}

I think it's rather self-explaining.

Michał Perłakowski
  • 88,409
  • 26
  • 156
  • 177