1
Input-
{
    "0": {
        "NAME": "ABC"
    },
    "1": {
        "NAME": "DEF"
    },
    "2": {
        "NAME": "GHI"
    },
    "3": {
        "NAME": "JKL"
    },
    "4": {
        "NAME": "MNO"
    }
}

I have this input. I want to get only names in array format like this Output-

["ABC", "DEF", "GHI", "JKL", "MNO"].

try

var arr =[]; for( var i in data ) { if (data.hasOwnProperty(i)){ arr.push(data[i]); } } 
3
  • 1
    what you tried so far ? Commented Jan 31, 2017 at 6:00
  • Parse the object and iterate Commented Jan 31, 2017 at 6:02
  • I was trying like this @AmeyaDeshpande var arr =[]; for( var i in data ) { if (data.hasOwnProperty(i)){ arr.push(data[i]); } } Commented Jan 31, 2017 at 6:08

4 Answers 4

2

Loop over the keys of the object and map its NAME property into an array.

var input = { "0": { "NAME": "ABC" }, "1": { "NAME": "DEF" }, "2": { "NAME": "GHI" }, "3": { "NAME": "JKL" }, "4": { "NAME": "MNO" } };

var result = Object.keys(input).map(function(key){
 return input[key].NAME;
});

console.log(result);

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

Comments

1

You will have to loop over object and get values.

Object.keys + Array.map

var data={0:{NAME:"ABC"},1:{NAME:"DEF"},2:{NAME:"GHI"},3:{NAME:"JKL"},4:{NAME:"MNO"}};

var result = Object.keys(data).map(x=>data[x].NAME)
console.log(result)

for..in

var data={0:{NAME:"ABC"},1:{NAME:"DEF"},2:{NAME:"GHI"},3:{NAME:"JKL"},4:{NAME:"MNO"}};

var result = [];
for(var key in data){
  result.push(data[key].NAME)
}
console.log(result)

Comments

0

Because the keys are numeric, or can easily be converted to a number, if you add a length property then you can utilize the built in array iteration methods. You could then use the reduce method to build your array.

Here is an ES6 example:

const input={0:{NAME:"ABC"},1:{NAME:"DEF"},2:{NAME:"GHI"},3:{NAME:"JKL"},4:{NAME:"MNO"}};

input.length = Object.keys(input).length;

const result = Array.prototype.reduce.call(input, 
    (output, element, index) => ((output[+index] = element.NAME), output), []);

console.log(result); // ["ABC", "DEF", "GHI", "JKL", "MNO"]

Comments

-1

var result={0:{NAME:"name1"},1:{NAME:"name2"},2:{NAME:"name3"}};
var array = [];

for(var i=0; i<=result.length-1; i++){
  array.push(result[i].NAME);
}
console.log(array)

1 Comment

Please use for..in on objects. for will not work as result is a single object and does not have a property length. Also, please add explanation to your answer. Just adding code is not good enough

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.