gpt4 book ai didi

javascript - 从多个数组属性创建对象

转载 作者:行者123 更新时间:2023-12-01 16:16:40 25 4
gpt4 key购买 nike

我正在遍历一个对象,该对象包含多个电话号码作为键和包含对象作为值的数组。

我编写了一个 reduce 方法,将所有计划组合在一起,除了一个问题。

如果您运行代码片段,您会看到 res 是:{trackingNumber: [ [Array] ]}

我需要对象看起来像:{trackingNumber: [Array]}

我继续遇到的问题是尝试通过初始索引弹出或切片或做任何事情使得第一个被连接的数组 (Object.values(res)) 基本上它将该数组的第一个对象枚举为前 7 个与跟踪号关联的值的元素。

{trackingNumber: [0:string, 1:string, 2:string, 3: {0 1 和 2 中的字符串对象}]}

如有任何帮助,我们将不胜感激。

let todayNewTollFree = [
{paymentSchedule: [{amount:500},{amount:500},{amount:500},{amount:500},{amount:500},{amount:500},],
tracking: "+18003160182"},
{paymentSchedule: [{amount:500},{amount:500},{amount:500},{amount:500},{amount:500},{amount:500},{amount:500},],
tracking: "+18003160182"
},
{
paymentSchedule: [],
tracking: "+12134105385"
},
{
paymentSchedule: [{amount:500},{amount:500},{amount:500},{amount:500},],
tracking: "+18007084605"
},
{
paymentSchedule:[{amount:500},{amount:500},{amount:500},{amount:500},{amount:500},],
tracking: "+18007100629"
}
]

let test = todayNewTollFree.reduce(function (res, obj) {
let key = obj.tracking;

if (res[key]) {
res[key] = res[key].map((key) =>
[key].flat().concat(obj.paymentSchedule)
);
} else res[key] = [obj.paymentSchedule];
for (const tracking in res) {
let values = Object.values(res[key]).flat();

console.log(tracking);
console.log(values);
}
return res;
}, {});

console.log(test)
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

for in 循环正确地创建了一个平面数组,但每次我必须返回并调用或将跟踪分配给新创建的数组的尝试都不起作用。

最佳答案

向对象添加新键时,不应将其放在数组文字 [...] 中(因为这会创建一个第一个元素为数组的数组),而应简单地分配数组本身到属性。此外,添加到数组时,Array#map 不是必需的,Array#concat 将完成这项工作。

let todayNewTollFree = [ {paymentSchedule: [{amount:500},{amount:500},{amount:500},{amount:500},{amount:500},{amount:500},], tracking: "+18003160182"}, {paymentSchedule: [{amount:500},{amount:500},{amount:500},{amount:500},{amount:500},{amount:500},{amount:500},], tracking: "+18003160182" }, { paymentSchedule: [], tracking: "+12134105385" }, { paymentSchedule: [{amount:500},{amount:500},{amount:500},{amount:500},], tracking: "+18007084605" }, { paymentSchedule:[{amount:500},{amount:500},{amount:500},{amount:500},{amount:500},], tracking: "+18007100629" } ]
let test = todayNewTollFree.reduce(function (res, obj) {
let key = obj.tracking;
if (res[key]) {
res[key] = res[key].concat(obj.paymentSchedule)
} else res[key] = obj.paymentSchedule;
return res;
}, {});
console.log(test)

关于javascript - 从多个数组属性创建对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63443158/

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