I want to create new JS array from an object. I explained my scenario as below.
Array 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"}
]
Array 2:
const arr2 = [
{PRICE: 6354, CODE: "SSW", WARN: "NBVC"},
{PRICE: 8637, CODE: "NNH", WARN: "MHYT"},
]
Expected output:
output = [
{CODE: "SSW", YARN: 4500, EXP: "NBVC", CARD: "MMN"},
{CODE: "NNH", YARN: 1540, EXP: "MHYT", CARD: "MMN"}
]
Explanation:
I want to compare arr1
and arr2
. If arr1.code
contain arr2.code
it should be in new array. It means arr1.code[2] = 'SSW'
. SSW
contains in arr2.code[0]
. Then arr1.code[2]
should be in new array. It same to arr1.code[3] = 'NNH'
. NNH
contains in arr2.code[1]
.
Tried code:
console.log(arr1.filter(({ CODE: code1 }) => arr2.some(({ CODE: code2 }) => code2 === code1));
When I tried to above code I am getting an error
Error in render: "TypeError: Cannot read property 'price' of undefined"
Help me to solve this problem.
question from:
https://stackoverflow.com/questions/65943110/how-to-create-new-js-array-from-another-js-array 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…