I have searched many sites to find the answer to this question, I do not know exactly how to describe it, so, excuse me. I have a .json file with this structure:
"ntest": [
{
"dane": [
{
"label": "Product A",
"mydane": [
{
"a": 20,
"y": "2018"
},
{
"a": 15,
"y": "2019"
},
{
"a": 35,
"y": "2020"
}
]
},
{
"label": "Product B",
"mydane": [
{
"a": 10,
"y": "2018"
},
{
"a": 15,
"y": "2019"
},
{
"a": 28,
"y": "2020"
}
]
}
]
and what I want is to receive something like this:
apart I want to have only one value of each year. I have already reached this point but I cannot access the data, and the result is as follow.
And this is my method.
getNewData(): void {
const ay: string[] = ['2018', '2019', '2020'];
const year = new Array();
this.getndata().subscribe((ko: any[]) => {
ko.forEach((lp) => {
lp.dane.forEach((el: { label: any; mydane: MyDane[]; }) => {
console.log(el.label);
console.log(el.mydane);
for (const ite of el.mydane) {
year.push(ite.y);
}
});
});
});
console.log(JSON.stringify(ay));
console.log(JSON.stringify(year));
// this.barChartLabels = yearray;
}
How can I get the result as in the first image? This is sringifi result
You can use a dictionary, also you can remove duplicates from the array, as Kelvin's said, then sorting them (dictionaries do that auto)
let data = { "ntest": [ { "dane": [ { "label": "Product A", "mydane": [ { "a": 20, "y": "2018" }, { "a": 15, "y": "2019" }, { "a": 35, "y": "2020" } ] }, { "label": "Product B", "mydane": [ { "a": 10, "y": "2018" }, { "a": 15, "y": "2019" }, { "a": 28, "y": "2020" } ] } ] } ] } let yearsDict = {} data.ntest[0].dane.forEach((dane) => { dane.mydane.forEach((obj) => { yearsDict[obj.y] = obj.a }) }) console.log(Object.getOwnPropertyNames(yearsDict))
For your problem, there are two easy solutions I can think of:
y
's from every dane
, only get them for the first one. That's assuming that the structure will be the same for all the dane
sThe latter can be easily done by storing your results in a Set instead of an array, which you can later convert to an array with Array.from(set)
. Sets don't store duplicates because of their nature.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.