-4

In my code I have a function that takes a json as an input:

[{
    "location": {},
    "_id": "5852d6fe29a15b4e6f9fc69d"
}, {
    "location": {},
    "_id": "5852d71529a15b4e6f9fc69e"
}, {
    "location": {},
    "_id": "5852d73229a15b4e6f9fc69f"
}, {
    "location": {},
    "_id": "5852d75b29a15b4e6f9fc6a0"
}]

I need to convert it so that the result is an array:

["5852d6fe29a15b4e6f9fc69d", "5852d6fe29a15b4e6f9fc69d",
 "5852d73229a15b4e6f9fc69f", "5852d75b29a15b4e6f9fc6a0"]

This json is a parameter to my function, basically the block code looks like this:

function parseJson(inputJson) {   
    if (inputJson!= undefined) {
        var outputArray = 
    }
}

what's the best way to parse that data?

Yosvel Quintero Arguelles
  • 17,270
  • 4
  • 37
  • 42
user3766930
  • 5,219
  • 10
  • 43
  • 98
  • 1
    simply use map function – Mahi Dec 21 '16 at 10:40
  • I'll bet you dollars to doughnuts that the input *isn't* JSON. JSON is a *textual notation* for data exchange. [(More.)](http://stackoverflow.com/a/2904181/157247) If you're dealing with JavaScript source code, and not dealing with a *string*, you're not dealing with JSON. (What's quoted at the top of the question would be invalid if it were JSON. For that matter, it's invalid as JavaScript, too.) – T.J. Crowder Dec 21 '16 at 10:40
  • Are you asking about parsing JSON or converting an array of objects into an array of numbers? I suspect you mean the latter and just don't understand what parsing means or what JSON is. – Quentin Dec 21 '16 at 10:41
  • 1
    Your first code block is neither valid JSON nor valid JavaScript. – Quentin Dec 21 '16 at 10:41

3 Answers3

0

Here is an example using Array.prototype.map():

var json = [{"location": {}, "_id": "5852d6fe29a15b4e6f9fc69d"}, {"location": {}, "_id": "5852d71529a15b4e6f9fc69e"}, {"location": {}, "_id": "5852d73229a15b4e6f9fc69f"}, {"location": {}, "_id": "5852d75b29a15b4e6f9fc6a0"}],
    arr = json.map(item => item._id);

console.log(arr);
Yosvel Quintero Arguelles
  • 17,270
  • 4
  • 37
  • 42
-1

You can use Array.prototype.map

let myJSON = [
    { location: {}, _id: 5852d6fe29a15b4e6f9fc69d },
    { location: {}, _id: 5852d71529a15b4e6f9fc69e },
    { location: {}, _id: 5852d73229a15b4e6f9fc69f },
    { location: {}, _id: 5852d75b29a15b4e6f9fc6a0 }
];
let myArray = myJSON.map(obj => obj._id);
Martial
  • 1,319
  • 13
  • 23
-1

You can use map method to transform an array into another array using a mapping function:

var oldArray = [ { "location": {}, "_id": "5852d6fe29a15b4e6f9fc69d" },
  { "location": {}, "_id": "5852d71529a15b4e6f9fc69e" },
  { "location": {}, "_id": "5852d73229a15b4e6f9fc69f" },
  { "location": {}, "_id": "5852d75b29a15b4e6f9fc6a0" } ];


var newArray = oldArray.map(function(element){
  return element._id;
});//map()

console.log( newArray );
Mohit Bhardwaj
  • 8,850
  • 3
  • 33
  • 62