gpt4 book ai didi

javascript - 如何从另一个 JS 数组创建新的 JS 数组

转载 作者:行者123 更新时间:2023-12-02 02:24:15 25 4
gpt4 key购买 nike

我想从一个对象创建新的 JS 数组。我解释了我的情况如下。

数组1:

const arr1 = [
{CODE: "PPM", YARN: 1987, EXP: "IUYT", CARD: "MMN"},
{CODE: "SSW", YARN: 4500, EXP: "NBVC", CARD: "MMN"},
{CODE: "YTR", YARN: 0740, EXP: "NBVC", CARD: "MMN"},
{CODE: "NNH", YARN: 1540, EXP: "MHYT", CARD: "MMN"}
]

数组2:

const arr2 = [
{PRICE: 6354, CODE: "SSW", WARN: "NBVC"},
{PRICE: 8637, CODE: "NNH", WARN: "MHYT"},
]

预期输出:

output = [
{CODE: "SSW", YARN: 4500, EXP: "NBVC", CARD: "MMN"},
{CODE: "NNH", YARN: 1540, EXP: "MHYT", CARD: "MMN"}
]

说明:

我想比较arr1arr2。如果 arr1.code 包含 arr2.code 它应该位于新数组中。这意味着arr1.code[2] = 'SSW'SSW 包含在 arr2.code[0] 中。那么 arr1.code[2] 应该在新数组中。与arr1.code[3] = 'NNH'相同。 NNH 包含在 arr2.code[1] 中。

尝试过的代码:

console.log(arr1.filter(({ CODE: code1 }) => arr2.some(({ CODE: code2 }) => code2 === code1));

当我尝试上面的代码时,出现错误

Error in render: "TypeError: Cannot read property 'price' of undefined"

帮我解决这个问题。

最佳答案

const arr1 = [
{CODE: "PPM", YARN: 1987, EXP: "IUYT", CARD: "MMN"},
{CODE: "SSW", YARN: 4500, EXP: "NBVC", CARD: "MMN"},
{CODE: "YTR", YARN: 0740, EXP: "NBVC", CARD: "MMN"},
{CODE: "NNH", YARN: 1540, EXP: "MHYT", CARD: "MMN"}
]

const arr2 = [
{PRICE: 6354, CODE: "SSW", WARN: "NBVC"},
{PRICE: 8637, CODE: "NNH", WARN: "MHYT"},
]

console.log(arr1.filter(({
CODE: code1
}) => arr2.some(({
CODE: code2
}) => code2 === code1))**)**;

我猜您可能错过了 console.log 语句中的括号 )。但是,您仍然没有在代码中使用 price 关键字。可能是其他问题。可以分享一下完整的功能吗?

关于javascript - 如何从另一个 JS 数组创建新的 JS 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65943110/

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