how to update a property in nested json array using ramdajs

36 views Asked by At

I have an array

[
  {
    "offerId": "123",
    "offerStatus": "ACTIVATED",
    "products": [
      {
        "productId": "1"
      }
    ]
  },
  {
    "offerId": "456",
    "offerStatus": "NOT_ACTIVATED",
    "products": [
      {
        "productId": "2"
      },
      {
        "productId": "3"
      }
    ]
  }
]

Want to push(copy) offerStatus into product object, so the expected output is

[
  {
    "offerId": "123",
    "offerStatus": "ACTIVATED",
    "products": [
      {
        "productId": "1",
        "offerStatus": "ACTIVATED"
      }
    ]
  },
  {
    "offerId": "456",
    "offerStatus": "NOT_ACTIVATED",
    "products": [
      {
        "productId": "2",
        "offerStatus": "NOT_ACTIVATED"
      },
      {
        "productId": "3",
        "offerStatus": "NOT_ACTIVATED"
      }
    ]
  }
]
1

There are 1 answers

0
Ori Drori On

Map the array, use the withSpec utility function (based on this answer) to update the products using the offerStatus of the parent. Then map products, and merge the current offerStatus:

const { pipe, applySpec, chain, mergeLeft, map, mergeRight } = R

const withSpec = pipe(applySpec, chain(mergeLeft)) // create new properties using a spec, and add to object

const fn = map(withSpec({
  products: ({ offerStatus, products }) => 
    map(mergeRight({ offerStatus }), products)
}))

const items = [{"offerId":"123","offerStatus":"ACTIVATED","products":[{"productId":"1"}]},{"offerId":"456","offerStatus":"NOT_ACTIVATED","products":[{"productId":"2"},{"productId":"3"}]}]

const result = fn(items)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.29.0/ramda.min.js" integrity="sha512-5x/n+aOg68Z+O/mq3LW2pC2CvEBSgLl5aLlOJa87AlYM1K8b8qsZ7NTHLe3Hu56aS2W0rgEgVCFA3RM12IXAGw==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>