gpt4 book ai didi

javascript - d3.nest() 键/值未定义值

转载 作者:行者123 更新时间:2023-11-29 20:45:57 24 4
gpt4 key购买 nike

在嵌套数据后,我试图从 key/values 中获取所有 n 个值 的数组。我已经设法 console.log 所有 n 个值 但我得到的最终结果是一个未定义的数组 [undefined, ... , undefined]。

//Nesting data by category
let updatedData = d3.nest()
.key(d => d.category)
.sortValues((a, b) => a.year - b.year)
.entries(data);

嵌套后的数据:

key: "clothing, beauty, & fashion"
values: Array(11)
0: {year: 2004, category: "clothing, beauty, & fashion", n: 141}
1: {year: 2005, category: "clothing, beauty, & fashion", n: 203}
2: {year: 2006, category: "clothing, beauty, & fashion", n: 195}
3: {year: 2007, category: "clothing, beauty, & fashion", n: 296}


key: "computers & internet"
values: Array(11)
0: {year: 2004, category: "computers & internet", n: 2489}
1: {year: 2005, category: "computers & internet", n: 2200}
2: {year: 2006, category: "computers & internet", n: 2114}
3: {year: 2007, category: "computers & internet", n: 2402}

现在获取所有 n 个值:

const nValues = [].concat.apply([], updatedData.map(d => d.values[d.values.forEach(d => console.log(d.n))]));
console.log(nValues);

我做错了什么?

最佳答案

您只需要映射到 values 键并为每个分组数据返回 n

 const nValues = data.map(group => group.values.map(e=> e.n))

const data = [
{
"key": "clothing, beauty, & fashion",
"values": [
{
"year": 2004,
"category": "clothing, beauty, & fashion",
"n": 141
},
{
"year": 2005,
"category": "clothing, beauty, & fashion",
"n": 203
},
{
"year": 2006,
"category": "clothing, beauty, & fashion",
"n": 195
},
{
"year": 2007,
"category": "clothing, beauty, & fashion",
"n": 296
}
]
},
{
"key": "computers & internet",
"values": [
{
"year": 2004,
"category": "computers & internet",
"n": 2489
},
{
"year": 2005,
"category": "computers & internet",
"n": 2200
},
{
"year": 2006,
"category": "computers & internet",
"n": 2114
},
{
"year": 2007,
"category": "computers & internet",
"n": 2402
}
]
}
]

const nValues = data.map(group => group.values.map(e=> e.n))
console.log(nValues)

关于javascript - d3.nest() 键/值未定义值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54556277/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com