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.
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))**)**;
I guess you might have missed a bracket ) in the console.log statement. But still, you have not used the price keyword in the code. Might be some other issue. Can you please share the full function?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.