0

How do I add value to object in an array of objects in Typescript?

Say I have an array of object like this:

[{name:'John',age:20}, {name:'Sam',age:26}, {name:'Will',age:2}]

What I want is dynamically generated property in each object of array as this:

[{name:'John',age:20, value:'John 20'}, {name:'Sam',age:26, value:'Sam 26' }, {name:'Will',age:2, value:'Will 2'}]

This is what I tried: I have a created a model for type checking and created a method in it which will return the value.

export class Names {
    name: string;
    age: number;
    constructor() {
    }
    getConcat() {
        return this.name + ' ' + this.age;
    }
}

Although when I get data from server of type Names[], I am not able to fetch the dynamically generated value. I am trying to get values like this:

this.somevariable:Names[]=[];  //declarartion
this.somevariable[0].getConcat() // inside a method after api call

How do I do that? Any help would be much appreciated. Thanks!

Amit Baranes
  • 7,398
  • 2
  • 31
  • 53
j asher
  • 1
  • 1
  • 2

3 Answers3

2

as you made the class for the purpose of typechecking - I'm guessing you mixed up javascript's class and typescript's interface:

an interface is only present during development, and gone in your actual production app. a class is a living js object that is compiled into a functioning object in your app.

an interface for typechecking may look like this:

interface Name {
  name: string;
  age: number;
  getConcat: () => string; // hints about the presence of a function that returns a string, within the typed object - but is not a function by itself!
}

while a class requires a bit modification

export class Names {
    name: string;
    age: number;

    constructor(name: string, age: number) { // pass arguments to initialize the class object
      this.name = name;
      this.age = age;
    }

    getConcat() {
        return this.name + ' ' + this.age;
    }
}

using interfaces, you could say that the array of names you have is of type Name[], meaning:

function getConcat () {
   return this.name + ' ' + this.age
}

const names: Name[] = [{name: 'a', age: 1, getConcat: getConcat }, {name: 'b', age: 2, getConcat: getConcat },...];

and throughout your code development, you will be hinted about the already preset getConcat method, and be warned if it is not there now, or in future.

But in order to use the class for both typechecking AND the getConcat function, you will have to map each object into a class:

const objects = [{name: 'a', age: 1}, {name: 'b', age: 2}];
const names: Name[] = objects.map(obj => new Name(obj.name, obj.age));

And now you can access any method you declared within Name class, for each item in names array.

You can actually mix the two up, initializing the js classes as shown above, while typechecking the class itself:

export class Name implements NameInterface {
    name: string;
    age: number;

    constructor(name: string, age: number) { 
      this.name = name;
      this.age = age;
    }

    getConcat() {
        return this.name + ' ' + this.age;
    }
}

And now you will be warned if your class object has not implemented any member of the NameInterface declared members (say you forgot to add the getConcat function within the class).

shuk
  • 1,745
  • 1
  • 14
  • 25
0

You want to insert new attribute then you should write like this: arr[i].value = arr[i].name + ' '+ arr[i].age;. Once you get data from API store it in an array and then do as shown below to update your array.

Following is working example:

arr = [{name:'John',age:20}, {name:'Sam',age:26}, {name:'Will',age:2}];

for(let i=0;i<3;i++){
    arr[i].value = arr[i].name + ' '+ arr[i].age;
}

console.log(arr);
Himanshu Singh
  • 2,117
  • 1
  • 5
  • 15
  • You don't seem to have read the question. This deals with the title but the content of the question deals with something very different. See the other answer https://stackoverflow.com/a/59505493/1915893 – Aluan Haddad Dec 27 '19 at 21:43
-1

arr = [{name:'John',age:20}, {name:'Sam',age:26}, {name:'Will',age:2}];



const generateValue = (items) => {
  return items.map(x=> {
    return {...x, value: `${x.name} ${x.age}`};
  });
};

arr = generateValue(arr);
console.log(arr);

You can create function like this

RICKY KUMAR
  • 643
  • 4
  • 11