Dwi Kurniawan
Dwi Kurniawan

Reputation: 3

How to compare two value that has same property of objects?

I have two data below:

const data1 = 
[
  {
    "Name": "Shoes",
    "SKU": "SKU001",
    "Quantity": 4
  },
  {
    "Name": "Sweater",
    "SKU": "SKU002",
    "Quantity": 2
  }
]
const data2 =
[
  {
    "DN": "DN0001",
    "SKU": "SKU001",
    "Quantity": 4
  },
  {
    "DN": "DN0002",
    "SKU": "SKU002",
    "Quantity": 4
  }
]

I want to compare the quantity of each SKU data1 with the quantity of each SKU data2 ( the same or not). How I can compare that?

Upvotes: 0

Views: 266

Answers (2)

Rajdeep D
Rajdeep D

Reputation: 3910

const data1 = 
[
  {
    "Name": "Shoes",
    "SKU": "SKU001",
    "Quantity": 4
  },
  {
    "Name": "Sweater",
    "SKU": "SKU002",
    "Quantity": 2
  }
]
const data2 =
[
  {
    "DN": "DN0001",
    "SKU": "SKU001",
    "Quantity": 4
  },
  {
    "DN": "DN0002",
    "SKU": "SKU002",
    "Quantity": 4
  }
]

let result = data1.map(d1 => data2.find(d2 => d2.SKU === d1.SKU)?.Quantity === d1.Quantity);

console.log(result);

Upvotes: 1

Goutham
Goutham

Reputation: 305

You can try like below

const data1 =
    [
        {
            "Name": "Shoes",
            "SKU": "SKU002",
            "Quantity": 4
        },
        {
            "Name": "Sweater",
            "SKU": "SKU002",
            "Quantity": 2
        }
    ]
const data2 =
    [
        {
            "DN": "DN0001",
            "SKU": "SKU001",
            "Quantity": 4
        },
        {
            "DN": "DN0002",
            "SKU": "SKU002",
            "Quantity": 4
        }
    ]

const result = data1.map((list) => {
    const hasItem = data2.find((data) => data.SKU === list.SKU);
    if (hasItem) {
        return hasItem.Quantity === list.Quantity;
    } else {
        return false
    }

})

console.log('res', result); // [true, false] 

Upvotes: 0

Related Questions