achai
achai

Reputation: 309

How to map two data with different length of attribute in angular

For example, I need to seed burger data with two attributes: name and vegetable. Burger1 has vegetable, but burger2 has not.

{
  "burgers": [
    {
      "name": "burger1",
      "vegetable": [
        “lettice”, “tomato”
      ]
    },
    {
      "name": "burger2"
    }
  ]
}

I would like to seed this burger data to database with seedService. The create request only requires “name” , and “vegetable” is optional.

How to achieve in angular or in typescript to seed all existing information for both burgers, even if one has optional attribute and the other one not?

The real data has more than 5 attributes are optional like vegetable, so I would try to avoid if else condition loop for all 5 attributes, unless there is a cleaner way.

I am fairly new to typescript. Thank you in advance!

Minimal example codes for reference:

const data = burger.json

data.map(res => 
  seedService.create(
  {
  “name”: res.name,
  “vegetable”: res.vegetable // fail here since burger two has no vegetable
  })
)

Upvotes: 0

Views: 108

Answers (2)

Shariq
Shariq

Reputation: 175

You can check if a given property is there in your object and with a ternary operator, You can assign the value of the property or null like :

const data = burger.json

data.map(res => 
  seedService.create(
  {
  “name”: res.name,
  “vegetable”: res.vegetable ? res.vegetable : null,
  })
)

Upvotes: 1

Apoorva Chikara
Apoorva Chikara

Reputation: 8773

You can use destructing and can initialise the property value if it doesn't exist.

const data = burger.json
const burgers = data?.burgers;
burgers.forEach(burger => 
  seedService.create(burger);
)

In your service method, do this:

public create ({name = null, vegetable = null}) {
   // do something
   console.log(name);
   console.log(vegetable);
}

Upvotes: 1

Related Questions