0

I have this json. I only care about the uniqueIDs.

How can I get ONLY the uniqueID values delivered back to me as a comma separated list, ie, 11111, 22222? (I need to create my own array.) I can't edit the json below - I am just trying to parse the value I care about out of it....

{
        products: [{
            type: "Unique",
            name: "Joe",
            description: "Joes Description",
            uniqueID: "11111"
        }, {
            type: "Unique",
            name: "Jane",
            description: "Janes Description",
            uniqueID: "22222"
        }]
}

Thought it would be this easy but its not...

$data['uniqueID'][0]
user3390251
  • 317
  • 2
  • 5
  • 22

3 Answers3

0

Use map function:

var foo = {
  metadata: {
    products: [{
      type: "Unique",
      name: "Joe",
      description: "Joes Description",
      uniqueID: "11111"
    } {
      type: "Unique",
      name: "Jane",
      description: "Janes Description",
      uniqueID: "22222"
    }]
  }
}
var ids = foo.metadata.products.map(x => x.uniqueID);

And if you are not familiar with arrow function:

var ids = foo.metadata.products.map(function(x){
    return x.uniqueID;
});
Arun Ghosh
  • 7,634
  • 1
  • 26
  • 38
0

The Underscore Way

You can use underscore js _.pluck() or _.map() function.

var data = {
  metadata: {
    products: [{
      type: "Unique",
      name: "Joe",
      description: "Joes Description",
      uniqueID: "11111"
    },
    {
      type: "Unique",
      name: "Jane",
      description: "Janes Description",
      uniqueID: "22222"
    }]
  }
};


//Use plunk method
var uniqueIDArr = _.pluck(data.metadata.products, 'uniqueID'); 

console.log(uniqueIDArr);
//=> ["11111", "22222"]

//Use map function
var uniqueIDArr = _.map(data.metadata.products, function(obj) {
  return obj.uniqueID;
}); 
console.log(uniqueIDArr);
//=> ["11111", "22222"]
<script src="https://cdn.jsdelivr.net/underscorejs/1.8.3/underscore-min.js"></script>
Community
  • 1
  • 1
Mohan Dere
  • 4,497
  • 1
  • 25
  • 21
0

You can use Array.prototype.map() to create a new array and chain a Array.prototype.join() to get the uniqueIDsString in a single line:

var obj = {metadata: {products: [{type: "Unique",name: "Joe",description: "Joes Description",uniqueID: "11111"}, {type: "Unique",name: "Jane",description: "Janes Description",uniqueID: "22222"}]}},
    uniqueIDsString = obj
        .metadata
        .products
        .map(function(product) {
            return product.uniqueID;
        })
        .join(', ');

console.log(uniqueIDsString);
Yosvel Quintero
  • 18,669
  • 5
  • 37
  • 46