gpt4 book ai didi

javascript - 映射数组元素并返回对象

转载 作者:行者123 更新时间:2023-11-28 17:10:05 26 4
gpt4 key购买 nike

我有一个像这样的对象数组:

var pools = [{
dce: 3,
lts: 2,
name: "nift nation",
},
{
dce: 1049.99,
lts: 104.999,
name: "NSG I.NS. Mark Select",
},
{
dce: 162,
lts: 36.157,
name: "Shift-Team Mark Select",
}
]

我得到:

[
{
"nift_nation": [
{
"nift_nationDollars": ""
},
{
"nift_nationUnits": ""
},
{
"nift_nationPercentage": ""
}
]
},
{
"NSG_I$NS$_Mark_Select": [
{
"NSG_I$NS$_Mark_SelectDollars": ""
},
{
"NSG_I$NS$_Mark_SelectUnits": ""
},
{
"NSG_I$NS$_Mark_SelectPercentage": ""
}
]
},
{
"Shift__Team_Mark_Select": [
{
"Shift__Team_Mark_SelectDollars": ""
},
{
"Shift__Team_Mark_SelectUnits": ""
},
{
"Shift__Team_Mark_SelectPercentage": ""
}
]
}
]

var pools = [{
dce: 3,
lts: 2,
name: "nift nation",
},
{
dce: 1049.99,
lts: 104.999,
name: "NSG I.NS. Mark Select",
},
{
dce: 162,
lts: 36.157,
name: "Shift-Team Mark Select",
}
]

var getFieldSuffix = function(rowFieldCount) {
switch (rowFieldCount) {
case 0:
return 'Dollars';
case 1:
return 'Units';
case 2:
return 'Percentage';
default:
return
}
};

var replacementMap = {
single_space: '_',
dot: '$',
hyphen: '__',
};

var replacer = function(str) {
return str.replace(/[ .-]/g, l => {
if (l == ".") return replacementMap["dot"];
if (l == " ") return replacementMap["single_space"];
return replacementMap["hyphen"];
});
};

var arrObj = pools.map(function(pool) {
return Object.assign({
[replacer(pool.name)]: ['Dollars', 'Units', 'Percentage'].map(function(suffix, index) {
return {
[replacer(pool.name) + getFieldSuffix(index % 3)]: ''
}
})
})
})

console.log(arrObj)

我想要:

{
{
"nift_nation": {
"nift_nationDollars": "",
"nift_nationUnits": "",
"nift_nationPercentage": "",
}
},
{
"NSG_I$NS$_Mark_Select": {
"NSG_I$NS$_Mark_SelectDollars": "",
"NSG_I$NS$_Mark_SelectUnits": "",
"NSG_I$NS$_Mark_SelectPercentage": "",
}
},
{
"Shift__Team_Mark_Select": {
"Shift__Team_Mark_SelectDollars": "",
"Shift__Team_Mark_SelectUnits": "",
"Shift__Team_Mark_SelectPercentage": "",
}
}
}

最佳答案

您可以使用reduce()方法代替map()。

像这样:

return Object.assign({
[replacer(pool.name)]: ['Dollars', 'Units', 'Percentage'].reduce(function(acc, suffix, index) {
acc[replacer(pool.name) + getFieldSuffix(index % 3)] = '';
return acc;
}, {})
})

不同之处在于,当您使用map时,您返回一个数组。而使用reduce,你会返回累加器的结果,在这种情况下,它是一个对象,然后会被修补到你的父对象中。

然后可以将其应用于整个转换,如下所示:

var arrObj = pools.reduce(function(acc, pool) {
acc[replacer(pool.name)] = ['Dollars', 'Units', 'Percentage'].reduce(function(acc, suffix, index) {
acc[replacer(pool.name) + getFieldSuffix(index % 3)] = '';
return acc;
}, {});
return acc;
}, {})

关于javascript - 映射数组元素并返回对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54688787/

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