Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
152 views
in Technique[技术] by (71.8m points)

javascript - How to create new JS array from another JS array

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...