0

I have this Object which I want to restructure as shown in the desired output below. The IngriId in desired output is just Date.now() I am struggling to rearrange this it seems impossible to me .Can this be done in javascript because I am very new to it and I am finding it hard to implement?

Input:

const Shopping = {
    "meatsOutput": [
      {
        "val": "Chicken breast"
      }
    ],
    "spicesOutput": [
      {
        "amount": "½ tsp",
        "val": "paprika"
      }
    ],
    "dairyOutput": [
      {
        "amount": "1/2 Cup",
        "val": "yogurt"
      },
      {
        "amount": "1/2 teaspoon",
        "val": "heavy cream"
      }
    ]
  }

Desired Output:

const ShoppingList = [
      {
          "data": [{
              "value": "Chicken breast",
              "ingrId": "202237423fm16787",
          }],
          "name": "meatsOutput",
      },
      {
          "data": [{
              "amount": "½ tsp",
              "value": "paprika",
              "ingrId": "20223742381r787",
          }],
          "name": "spicesOutput",
      },
      {
          "data": [{
              "amount": "1/2 Cup",
              "value": "yogurt",
              "ingrId": "202237423816787",
          }, ],
          "name": "dairyOutput",
      }
  ]
6
  • 1
    "Can this be done in javascript" - yes. Commented Oct 14, 2020 at 14:55
  • where does ingrId come from? Commented Oct 14, 2020 at 14:55
  • @TKoL - as stated by OP - just Date.now() Commented Oct 14, 2020 at 14:56
  • 1
    What's the output case for dairyOutput when there are two ingredients? Commented Oct 14, 2020 at 14:56
  • @LeGEC, don't remind me. My flight to Göteborg got canceled. Commented Oct 14, 2020 at 15:06

1 Answer 1

1

Using Object.entries, you can generate the [key, value] pair array, and then, using Array.prototype.map, you can change that array to the result you want.

const input = {
  "meatsOutput": [{
    "val": "Chicken breast"
  }],
  "spicesOutput": [{
    "amount": "½ tsp",
    "val": "paprika"
  }],
  "dairyOutput": [{
      "amount": "1/2 Cup",
      "val": "yogurt"
    },
    {
      "amount": "1/2 teaspoon",
      "val": "heavy cream"
    }
  ]
};

const result = Object.entries(input).map(([key, value]) => ({
  name: key,
  data: value.map((item) => ({
    ...item,
    ingrId: Date.now()
  }))
}));
console.log(result);

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

2 Comments

Hi thank you so much for this Answer!!!! . How would I manipulate this if the input was wrapped in an array?
If input is array, you can make like this. const result = input.map((item) => Object.entries(item)...same...);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.