1

I have the following user object in my application:

let user = {name: "John", dob:"1995-10-15", metadata: {}}

The metadata property of my object is an empty object. On user input, I want to create a new property in the metadata object such as:

<input [(ngModel)]="user.metadata.childrenNumber" placeholder="Enter number of children"></input>

So far so good, everything works as expected. However, the childrenNumber property I have stored in an array:

let metaDataOptions = ['childrenNumber', 'workStatus', 'education'];

How can I reference the property's name I wish to be created from that array? For the case above I tried to do something like this:

// i is index from ngFor. i can be 0, 1 or 2
<input [(ngModel)]="user.metadata.metaDataOptions[i]" placeholder="Enter number of children"></input>

However, this does not work. How can I achieve the result I desire?

6
  • You can simply use [(ngModel)]="user.metadata[i]" just remove metaDataOptions Commented Aug 29, 2018 at 12:20
  • @RohitSharma I need to store the input of the user in metadata using the names from the metaDataOptions and not using numbers. Commented Aug 29, 2018 at 12:23
  • Have you tried user.metadata[metaDataOptions[0]] = 1 to create metaDataOptions key inside metaData object? Commented Aug 29, 2018 at 12:24
  • 1
    @lamOptimus Sure! The you can use [(ngModel)]="user.metadata[metaDataOptions[i]]" Commented Aug 29, 2018 at 12:25
  • @RohitSharma Thank you. This did the trick for me! Although, I can't seem to be able to mark your answer as accepted. Thank you again, take my upvote. Commented Aug 29, 2018 at 12:30

3 Answers 3

2

Keep below object as it is.

let user = {name: "John", dob:"1995-10-15", metadata: {}}
let metaDataOptions = ['childrenNumber', 'workStatus', 'education']

You can create object property inside the metadata object using below line of code.

<input [(ngModel)]="user.metadata[metaDataOptions[i]]" placeholder="Enter number of children"></input>
Sign up to request clarification or add additional context in comments.

Comments

1

You can just let it be

let user = {name: "John", dob:"1995-10-15", metadata: { 'childrenNumber' : null}}

and then

<input [(ngModel)]="user.metadata.childrenNumber" placeholder="Enter number of children"></input>

Comments

0

use the index 0

<input [(ngModel)]="user.metadata.metaDataOptions[0]" placeholder="Enter number of children"></input>

1 Comment

Here you can use like: user.metadata[metaDataOptions[0]], but it is limited to the first index only.

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.