0

Sorry new to typescript, I have this array of object, i need to insert another property type with value Customer for all objects.

//this is printed out in browser's developer mode, that's why the index is there
0: {name: "Ken", address: "USA"}
1: {name: "Peter", address: "USA"}

In the final array, it will be:

0: {name: "Ken", address: "USA", type: "Customer"}
1: {name: "Peter", address: "USA", type: "Customer"}

Something like:

this.users.forEach(function (user) {
    user.type: "Customer"
});

Tried to search around but not able to find the answer, how do i achieve the above?

1
  • 3
    Your sample is almost correct, just replace : to =. Commented Aug 19, 2021 at 9:18

3 Answers 3

2
 this.users = this.users.map(item => ({...item, type: "Customer"}))
Sign up to request clarification or add additional context in comments.

Comments

2

Try

this.users = this.users.map(function (user) {
    user.type =  "Customer"
    return user;
});

2 Comments

Why use map() instead of forEach()? You're mutating the objects itself anyway.
forEach is fine here too. I just tend to use map whenever I am mutating an object. It helps me detect where I am mutating objects in code easily
0

Change your user.type: "Customer" to user.type = "Customer" and it should work

let users = [{name: "Ken", address: "USA", type: "Customer"}]

users.forEach(function (user) {
    user.type = "Customer"
});

console.log(users)

Comments

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.