Reputation: 581
I have an array of objects and what i want to do is seperate entries based on if a value equals something. I'm reading my data off of a csv and changing some string into ints like this
d3.csv('mydata.csv', function(error, data){
data.forEach(function(d){
d["Fruits"] = +d["Fruits"]
d["Stores"] = +d["Stores"]
d["Names of Fruits"] = d["Names of Fruits"]
});
});
This is how my original data looks. mydata
Array(10) [ {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…} ]
The objects looks like this
"Fruits": 5
"Stores": 22
"Names of Fruits": "oranges",
"Fruits": 100
"Stores": 3
"Names of Fruits": "apples",
"Fruits": 10
"Stores": 300
"Names of Fruits": "pear",
"Fruits": 10
"Stores": 300
"Names of Fruits": "apple",
etc etc. to get this data i can call console.log(data) and all the above will show up in the console. I want to be able to separate these based on "Names of Fruits" values. so potentially would want to call console.log(appleData) and the results will be
"Fruits": 100
"Stores": 3
"Names of Fruits": "apples",
"Fruits": 10
"Stores": 300
"Names of Fruits": "apple",
same with orangeData, pearData etc etc
In order to do this i have tried
d3.csv('mydata.csv', function(error, data){
appleData = data.forEach(function(d){
if(d["Names of Fruits"] =="apple"){
d["Fruits"] = +d["Fruits"]
d["Stores"] = +d["Stores"]
d["Names of Fruits"] = d["Names of Fruits"]
}
});
orangeData = data.forEach(function(d){
if(d["Names of Fruits"] =="orange"){
d["Fruits"] = +d["Fruits"]
d["Stores"] = +d["Stores"]
d["Names of Fruits"] = d["Names of Fruits"]
}
});
});
Upvotes: 0
Views: 462
Reputation: 108512
Lots of ways to do this; here's a couple examples. The first uses d3.nest and turns the data into an array of arrays with the outer key being the name of the fruit. The second is a little hand-rolled code, which returns an object with properties of each fruit. What works best really depends on your larger use case.
<!DOCTYPE html>
<html>
<head>
<script data-require="[email protected]" data-semver="4.0.0" src="https://d3js.org/d3.v4.min.js"></script>
</head>
<body>
<script>
var data = [{
"Fruits": 5,
"Stores": 22,
"Names of Fruits": "oranges"
}, {
"Fruits": 100,
"Stores": 3,
"Names of Fruits": "apple"
},
{
"Fruits": 10,
"Stores": 300,
"Names of Fruits": "pear"
},
{
"Fruits": 10,
"Stores": 300,
"Names of Fruits": "apple"
}
];
console.log(
d3.nest()
.key(function(d) { return d["Names of Fruits"]; })
.entries(data)
);
var rv = {};
data.forEach(function(d){
if (!rv[d["Names of Fruits"]]) rv[d["Names of Fruits"]] = [];
rv[d["Names of Fruits"]].push(d);
});
console.log(rv);
</script>
</body>
</html>
Upvotes: 1