gpt4 book ai didi

javascript - 需要帮助从现有阵列创建新阵列

转载 作者:行者123 更新时间:2023-11-30 06:14:10 24 4
gpt4 key购买 nike

我有一个这样的数组:

const foo = [{
cur: "GBT",
val: [800, 450]
},
{
cur: "USD",
val: 100
},
{
cur: "EUR",
val: 200
},
{
cur: "GBT",
val: [100, 250]
}]

我想从上面的数组中得到下面的结构:

   [{
id: 0,
cur: "GBT",
val: 800
},

{
id: 1,
cur: "GBT",
val: 450
},
{
id: 2,
cur: "USD",
val: 100
},

{
id: 3,
cur: "EUR",
val: 200
},

{
id: 4,
cur: "GBT",
val: 100
},

{
id: 5,
cur: "GBT",
val: 250
}]

这是我尝试过的:

foo.reduce((x, y, i, a) => {
let resObj = {};
if (Array.isArray(y.val)) {
let cnt = 0;
(a.indexOf(y) === 0 ? cnt : cnt += i)
for (let j = 0; j < y.val.length; j++) {
const obj = {};
obj["id"] = cnt;
obj["value"] = y.val[j]
obj["currency"] = y.cur;
x.push(obj);
cnt++;
}
} else {
let cnt = 1
resObj["id"] = i + cnt;
resObj["value"] = y.val;
resObj["currency"] = y.cur;
}
return x.concat(resObj)
}, [])

Bugs Observed 1. When reduce function finds the next val of the object which is of type array, it is not increasing the counter, so the id is equal to the previous counter. 2. I also want to know how can i avoid creating blank object if the object has val which is an array, not sure what is the actual reason for this to happen. Please find the result attachment enter image description here

最佳答案

Array.prototype.reduce() 可能对您有所帮助。 reduce() 回调有两个参数,第一个参数是旧的/以前的迭代值,第二个参数是当前的迭代值/元素。

因此,使用此函数,我们可以将当前迭代值保存为上一次迭代值(总值)。

The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.

const foo = [{cur: "GBT",val: [800, 450]},{cur: "USD",val: 100},{cur: "EUR",val: 200},{cur: "GBT",val: [100, 250]}]

const result = foo.reduce((acc, cur) => {
if (Array.isArray(cur.val)) {
cur.val.map(val => !!(acc.push({id: acc.length, cur: cur.cur, val: val})))
} else {
acc.push({id: acc.length, cur: cur.cur, val: cur.val})
}
return acc
}, [])
console.log(result)

关于javascript - 需要帮助从现有阵列创建新阵列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57242932/

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