This may be extremely simple but I've not been able to figure out how to iterate over and access the properties in the following mix (I think) of arrays and nested objects:
myFilters = {
"color_Filter": [{
"name": "BLUE",
"count": 1,
"dataId": "BLUE"
},
{
"name": "Black",
"count": 5,
"dataId": "Black"
},
{
"name": "Blue",
"count": 14,
"dataId": "Blue"
}
],
"size_Filter": [{
"name": "10",
"count": 16,
"dataId": "10"
},
{
"name": "12",
"count": 16,
"dataId": "12"
}
]
}
What would the correct looping structure be here to pull out name, count etc from the above? The desired output is to output a string from the above with color_Filter=BLUE,Black,Blue/size_Filter=10,12
I've tried a few different approaches and none of them have been successful so far.
You could map the entries of the object and create a string for each key. Get the name from the value array using map. Then join the array of strings with a /
const myFilters = {color_Filter:[{name:"BLUE",count:1,dataId:"BLUE"},{name:"Black",count:5,dataId:"Black"},{name:"Blue",count:14,dataId:"Blue"}],size_Filter:[{name:"10",count:16,dataId:"10"},{name:"12",count:16,dataId:"12"}]};
const output = Object.entries(myFilters)
.map(([k,arr]) => `${k}=${arr.map(a => a.name)}`)
.join("/")
console.log(output)
Related
Im trying to build in Javascript a Table of Nutritional Values, Quantity and Daily Percentage.
I've saved JSON data in this way:
data : [
{
"recipe": {
"totalNutrients": {
"ENERC_KCAL": {
"label": "Energy",
"quantity": 122.67497750000001,
"unit": "kcal"
},
"K": {
"label": "Potassium",
"quantity": 255.9084202548212,
"unit": "mg"
},
"FAT": {
"label": "Fat",
"quantity": 11.89368915,
"unit": "g"
},
"ZN": {
"label": "Zinc",
"quantity": 0.328366321935265,
"unit": "mg"
},
"FIBTG": {
"label": "Fiber",
"quantity": 3.609618250000001,
"unit": "g"
},
"SUGAR": {
"label": "Sugars",
"quantity": 0.5078356,
"unit": "g"
}
}
}
}]
I want to get ENERC_KCAL, FAT and the others values in the array "KEYS" from JSON data.
keys = ['ENERC_KCAL', 'FAT', 'CHOCDF', 'FITBG', 'SUGAR', 'PROCNT', 'CHOLE', 'NA'];
valNut = data[0].recipe.totalNutrients;
Is there a way to accomplish the following instruction:
energyValue = valNut.ENERC_KCAL.quantity + ' ' + valNut.ENERC_KCAL.unit
using instead the values of the array in a loop?
for(h=0; h<keys.length; h++){
energyValue = valNut.keys[h].quantity + ' ' + valNut.keys[h].unit
}
P.S. Sorry for the bad english.
To do what you require you could loop through the keys using map() to build a new array of the matching totalNutrients key objects. Something like this:
let data = [{recipe:{totalNutrients:{ENERC_KCAL:{label:"Energy",quantity:122.67497750000001,unit:"kcal"},K:{label:"Potassium",quantity:255.9084202548212,unit:"mg"},FAT:{label:"Fat",quantity:11.89368915,unit:"g"},ZN:{label:"Zinc",quantity:.328366321935265,unit:"mg"},FIBTG:{label:"Fiber",quantity:3.609618250000001,unit:"g"},SUGAR:{label:"Sugars",quantity:.5078356,unit:"g"}}}}];
let keys = ['ENERC_KCAL', 'FAT', 'CHOCDF', 'FITBG', 'SUGAR', 'PROCNT', 'CHOLE', 'NA'];
let filteredNutrientData = keys.map(key => data[0].recipe.totalNutrients[key]).filter(v => v);
console.log(filteredNutrientData);
Note that the final .filter(v => v) is to remove the undefined values resulting from searching for a non-existent key in the totalNutrients object.
Currenly using Angular with lodash to do some additional usability but currently hitting a roadblock.
I have the following arrays:
{
"Result": [
{
"Name": "marketeerBoston",
"Label": "Week25",
"Total": 251200,
"Specific": [
{
"Label": "3",
"Value": 25,
},
{
"Label": "4",
"Value": 250,
}
]
},
{
"Name": "marketeerJersey",
"Label": "Week25",
"Total": 776090,
"Specific": [
{
"Label": "1",
"Value": 32,
},
{
"Label": "2",
"Value": 37,
}
]
},
],
}
I really need to have the Value summed up from both array objects (so I got 344).
How to achieve that with lodash?
With lodash, you can use nested _.sumBy() calls:
const data = {"Result":[{"Name":"marketeerBoston","Label":"Week25","Total":251200,"Specific":[{"Label":"3","Value":25},{"Label":"4","Value":250}]},{"Name":"marketeerJersey","Label":"Week25","Total":776090,"Specific":[{"Label":"1","Value":32},{"Label":"2","Value":37}]}]}
const result = _.sumBy(data.Result, obj => _.sumBy(obj.Specific, 'Value'))
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.20/lodash.min.js" integrity="sha512-90vH1Z83AJY9DmlWa8WkjkV79yfS2n2Oxhsi2dZbIv0nC4E6m5AbH8Nh156kkM7JePmqD6tcZsfad1ueoaovww==" crossorigin="anonymous"></script>
I am fairly new to Vue and JS but I am making API calls and getting a JSON response then sending the response to an empty array. How do I get the ID of each object in the array?
The array that the response is being pushed to is structured like this
groups: [
{
"id": "0",
"name": "a",
"price": 5
},
{
"id": "1",
"name": "b",
"price": 5
},
{
"id": "2",
"name": "c",
"price": 5
}
]
I'd like to pull the Id of each object and push the values to an empty array
for(var group in this.groups) {
if (this.groups.hasOwnProperty(0)) {
this.group = this.groups[0];
this.groupsId.push(this.innerObj);
}
}
The error I'm getting is saying Cannot read property '0' of undefined at eval
Ideally I'd like an array that has all the Ids of each object.
this.groups.hasOwnProperty(0) should be group.hasOwnProperty('id')
Use Array.prototype.map() to iterate over an array of objects and collect every ID into a new array:
const res = {
groups: [{
"id": "0",
"name": "a",
"price": 5
},
{
"id": "1",
"name": "b",
"price": 5
},
{
"id": "2",
"name": "c",
"price": 5
}
]
};
const ids = res.groups.map(obj => { // you use this.groups
if(obj.hasOwnProperty('id')) return obj.id;
});
console.log(ids)
There is the Array.map() method:
this.groupsId = this.groups.map(i => i.id);
If you already have elements in this.groupsId you can append the ids using Array.concat():
this.groupsId = this.groupsId.concat(this.groups.map(i => i.id));
You can use Array.prototype.reduce to loop and check if there's id.
const groups = [
{"name": "a","price": 5},
{"id": "1","name": "b","price": 5},
{ "id": "2","name": "c","price": 5}
];
const list = groups.reduce((groupIds, group) => group.id ? [...groupIds, group.id] : groupIds, []);
console.log(list);
I am fetching data from different sources and have ended up with a several correctly formed json objects and one which has parent keys like below:
{
"0": {
"term_id": 3,
"name": "Burger"
},
"1": {
"term_id": 6,
"name": "Chicken"
},
"2": {
"term_id": 12,
"name": "Mexican"
},
}
How can I remove 0, 1, 2, 3 etc while also preserving other correctly structured objects? I am using lodash elsewhere in this project
This object with parent keys is being inserted into an array of multiple objects via a map
Promise.all(promises)
.then(results => {
let valueArr = [];
Object.keys(results).forEach(function(key) {
valueArr = [results[key]]
});
this.setState({ categorySelectOptions: valueArr });
})
This is a screenshot of the output with the problem:
All you need to do is push into the array instead of assigning. Use this -
Object.keys(results).forEach(function(key) {
valueArr.push(results[key])
});
Use Object.values
const data = {
"0": {
"term_id": 3,
"name": "Burger"
},
"1": {
"term_id": 6,
"name": "Chicken"
},
"2": {
"term_id": 12,
"name": "Mexican"
},
};
console.log(Object.values(data));
Hi I am trying to make a stacked bar chart using Highcharts, but the way the data has to be formatted to be consumed as a a series is tripping me up.
series: [{
name: 'John',
data: [5]
}, {
name: 'ee',
data: [2]
}, {
name: 'aa',
data: [7]
},{
name: 'zz',
data: [4]
},{
name: 'Joe',
data: [3]
}]
That is how one of the examples is on their site for a stacked bar chart. I am using $http.get() to originally get data from a webservice, in JSON format like so :
{
"id": 13,
"name": "JohnSnow",
"totalScore": 5.239947894580996,
"models": [
{
"id": 0,
"name": "Grey",
"score": 75.5
},
{
"id": 1,
"name": "Black",
"score": 1.2355425046127677
},
{
"id": 2,
"name": "Purple",
"score": 24.0705126173457
},
{
"id": 3,
"name": "Teal",
"score": 28.981312850901684
},
{
"id": 4,
"name": "Yellow",
"score": 31.373482114014525
},
{
"id": 5,
"name": "Green",
"score": 22.02040979235661
},
{
"id": 6,
"name": "Red",
"score": 11.137161646416322
},
{
"id": 7,
"name": "Blue",
"score": 25.83014182677578
},
{
"id": 8,
"name": "Orange",
"score": 4.793888180490194
}
]
}
My original approach was to go through the returned data from the $http.get() call and add a JSON object to an array that I would then set series equal to but that isn't working out too well. What are some other options, or are there easier ways to get it in the format. The data has to stay in that format on the webservice, so changing is out of the question. I have a plunker I am trying to get working here.
interesting question, I normally use either angular.forEach or a library called underscore to handle data processing in angularJS. Here is the forEach version.
data = $http.get(); // suppose you have the data
result = [];
angular.forEach(data.models, function(item) {
// simple way is to take item as the original form
result.push(item);
// or do your own way
result.push({
name: item.name,
data: [item.score]
});
});
Now the result variable is the one you want now.