0

I have an object and an array. The object looks like this.

const saleProducts = {
  category: "Books",
  product_skus: [
    "14003696",
    "14003915",
    "14003699",
    "14003698",
    "14003697",
    "14003917",
  ],
};

The array has several objects inside and looks something like this:

const productDetails = [
  {
    _id: "618182229285e8d8f86be2d9b3",
    name: "JS for Dummies",
    description:
      "Learning Manual",
    category: "books",
    sku: "14003696",
    price: {
      amount: 20
    },
    images: [
      "https://uri1.png",
      "https://uri2.png",
    ],
}

As you can see, the 'sku' in the array (bookDetails) matches one of the skus in 'saleProducts'. So I would like to replace the sku with the object that has all the details. In the end, I would like the 'saleProducts' to look like this:

const saleProducts = {
  category: "Books",
  product_skus: [
    {
    _id: "618182229285e8d8f86be2d9b3",
    name: "JS for Dummies",
    description:
      "Learning Manual",
    category: "books",
    sku: "14003696",
    price: {
      amount: 20
    },
    images: [
      "https://uri1.png",
      "https://uri2.png",
    ],
]
} // ... etc. replacing each sku with the full details.

what is the simplest way to do this?

0

1 Answer 1

2

You can use a map function to replace all sku with corresponding details data:

saleProducts.product_skus = saleProducts.product_skus.map(sku => 
  productDetails.find(details => details.sku === sku) || sku
);

const saleProducts = {
  category: "Books",
  product_skus: [
    "14003696",
    "14003915",
    "14003699",
    "14003698",
    "14003697",
    "14003917",
  ],
};

const productDetails = [
  {
    _id: "618182229285e8d8f86be2d9b3",
    name: "JS for Dummies",
    description:
      "Learning Manual",
    category: "books",
    sku: "14003696",
    price: {
      amount: 20
    },
    images: [
      "https://uri1.png",
      "https://uri2.png",
    ],
  },
  {
    _id: "MOCK_1",
    name: "CSS for Dummies",
    description: "Learning Manual",
    category: "books",
    sku: "14003697",
    price: {
      amount: 10
    },
    images: [
      "https://uri3.png",
      "https://uri4.png",
    ],
  }
];

// replace sku with corresponding details data
saleProducts.product_skus = saleProducts.product_skus.map(sku => productDetails.find(details => details.sku === sku) || sku);

console.log(saleProducts);

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.