gpt4 book ai didi

javascript - 在构造函数中遍历对象内部的对象?

转载 作者:行者123 更新时间:2023-11-30 14:41:04 28 4
gpt4 key购买 nike

在构造函数中,我试图创建一个对象。

在该对象中,我已经为某些数组使用了 map 函数。

当我尝试遍历一个对象时出现了挑战,因为我不能在对象上使用 map 函数。我也试过在这个对象中使用 for in 函数,但看起来,在对象创建中使用 for in 是无效的 JS。

我的目标是遍历 individualData 对象(就像数组的普通映射函数一样)。

我尝试将 data: data.individualData 移动到 map 函数中。这对我的预期结果不起作用。

这是我的代码:

labelsArray = ['Breakfast', 'Lunch', 'Dinner'];

data = {
miniLabelsArray: ['Egg', 'Soup', 'Steak'],
type: ['Vegetarian', 'Vegan', 'Normal'],
individualData: [{
John: ['1', '2', '3'],
Paul: ['10', '20', '30'],
Kate: ['100', '200', '300']
}]
};

function CreateData(data, someNewObj) {

this.someNewObj = {
labels: labelsArray,
datasets:
data.miniLabelsArray.map((miniLabelsArray, i) => ({
miniLabel: data.miniLabelsArray[i],
type: data.type[i],
})),
data: data.individualData
};
};

var testing = new CreateData(data);

console.log('testing', testing.someNewObj);

https://codepen.io/anon/pen/qoMdoe?editors=1111

预期结果:

 ...
"datasets": [
{
"miniLabel": "Egg",
"type": "Vegetarian",
"data": ["1", "2", "3"] // DIFFERENCE HERE
},
{
"miniLabel": "Soup",
"type": "Vegan",
"data": ["10", "20", "30"] // DIFFERENCE HERE
},
{
"miniLabel": "Steak",
"type": "Normal",
"data" :["100", "200", "300"] // DIFFERENCE HERE
}
...

谢谢

最佳答案

我将您的方法更新为 This。

datasets: data.miniLabelsArray.map((value, index)=>({
miniLabel: value,
type: data.type[index],
data: data.individualData[0][keys[index]]
}))

这里重要的是 var keys = Object.keys(data.individualData[0])

数据:data.individualData[0][keys[index]]

labelsArray = ['Breakfast', 'Lunch', 'Dinner'];

data = {
miniLabelsArray: ['Egg', 'Soup', 'Steak'],
type: ['Vegetarian', 'Vegan', 'Normal'],
individualData: [{
John: ['1', '2', '3'],
Paul: ['10', '20', '30'],
Kate: ['100', '200', '300']
}]
};

function CreateData(data, someNewObj) {
//get keys from [individualData] property
var keys = Object.keys(data.individualData[0])
this.someNewObj = {
labels: labelsArray,
// here we map every [miniLabelsArray] value and get the [type] and [individualData] depending on the index that we are.
datasets: data.miniLabelsArray.map((value, index)=>({
miniLabel: value,
type: data.type[index],
// here we get the real key of [data.individualData] using the key we took at the beginning like this : keys[index], and with that key we get the value in [data.individualData[0]]
data: data.individualData[0][keys[index]]
}))

};
};

var testing = new CreateData(data);

console.log('testing', testing.someNewObj);

关于javascript - 在构造函数中遍历对象内部的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49654808/

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