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



我想从一个对象创建新的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'arr2.code[0]中包含SSW。然后arr1.code[2]应该在新的数组。和arr1.code[3] = 'NNH'一样。NNH包含在arr2.code[1]

尝试代码:

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

当我尝试上面的代码,我得到一个错误

渲染错误:"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声明。但是,您仍然没有使用价格关键字。可能是其他问题。你能分享一下完整的功能吗?

相关内容

  • 没有找到相关文章

最新更新