Home > other >  How to sort the array which is in key value pair in react?
How to sort the array which is in key value pair in react?

Time:05-30

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
const itemsData = [
  {
    key: 1,
    src: "https://www.davidjones.com/productimages/cart/1/2384359_21556984_6888675.jpg",
    title: "Nautica ANTIGUA PADDED JACKET DARK NAVY",
    price: 245,
    colour: "459 DARK NAVY",
    Size: "M",
    Qty: "1",
  },
  {
    key: 2,
    src: "https://www.davidjones.com/productimages/cart/1/2384359_21556984_6888675.jpg",
    title: "Nautica ANTIGUA PADDED JACKET DARK NAVY",
    price: 245,
    colour: "459 DARK NAVY",
    Size: "M",
    Qty: "1",
  },
  {
    key: 3,
    src: "https://www.davidjones.com/productimages/cart/1/2384359_21556984_6888675.jpg",
    title: "Nautica ANTIGUA PADDED JACKET DARK NAVY",
    price: 245,
    colour: "459 DARK NAVY",
    Size: "M",
    Qty: "1",
  },
];

`

I am trying to filter this array. Just to get a new array as only with price array. Please help me to make a new array that has only price data

const price = [245,245,245]

CodePudding user response:

You want to use map function on an array and transform the objects inside of it to a new value. Something like this

const itemsData = [
{
key: 1,
src: "https://www.davidjones.com/productimages/cart/1/2384359_21556984_6888675.jpg",
title: "Nautica ANTIGUA PADDED JACKET DARK NAVY",
price: 245,
colour: "459 DARK NAVY",
Size: "M",
Qty: "1",
},
{
key: 2,
src: "https://www.davidjones.com/productimages/cart/1/2384359_21556984_6888675.jpg",
title: "Nautica ANTIGUA PADDED JACKET DARK NAVY",
price: 245,
colour: "459 DARK NAVY",
Size: "M",
Qty: "1",
},
{
key: 3,
src: "https://www.davidjones.com/productimages/cart/1/2384359_21556984_6888675.jpg",
title: "Nautica ANTIGUA PADDED JACKET DARK NAVY",
price: 245,
colour: "459 DARK NAVY",
Size: "M",
Qty: "1",
},
];

const prices = itemsData.map(item => item.price)

console.log(prices)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

CodePudding user response:

itemsData.filter(item=>item.key === 1);
You can filter any item in this array like this! Thanks! 

CodePudding user response:

It's a simple mapping: itemsData.map(item => item.price)

Also, it's not really React related, more like a Javascript question.

  • Related