mfroese
mfroese

Reputation: 309

Extracting an object from an array in Javascript

I am working on a D3.JS chart using an array named "dataset" where each entry is an object with a key and value attributes, such as the following:

dataset= 
 [
 {"key":"alpha", "value": [ {}, { } ...]},
 {"key":"beta", "value": [ { }, { } ...]},
 {"key":"gamma", "value": [ {}, { } ...]},
 {"key":"delta", "value": [ { }, { } ...]}
 ];

I need to extract one of those objects to create a new array. I have tried the following:

filteredDataset = dataset.filter(function(d){ console.log("d",d); if(d.key === "gamma") return d});

I can see in the console that I am accessing each object in the dataset, but the resulting filteredDataset comes out empty. What am I doing wrong?

Upvotes: 0

Views: 121

Answers (2)

Rick Lancee
Rick Lancee

Reputation: 1659

dataset.filter(function(d){return d.key === 'gamma';});
This returns the data where key === gamma.

https://github.com/mbostock/d3/wiki/Selections#filter

Upvotes: 0

Matyas
Matyas

Reputation: 13702

For clarity filter should be used by returning a boolean:

Like:

filteredDataset = dataset.filter(function(d){ return d.key === "gamma"})

And on my end the code

var dataset = [
     {"key":"alpha", "value": [ {}, { }]},
     {"key":"beta", "value": [ { }, { }]},
     {"key":"gamma", "value": [ {}, { }]},
     {"key":"delta", "value": [ { }, { }]}
]; 
filteredDataset = dataset.filter(function(d){ return d.key === "gamma"})

Outputs:

[ { key: 'gamma', value: [ {}, {} ] } ]

So please double check your code

Upvotes: 1

Related Questions