Diego Oliveira
Diego Oliveira

Reputation: 121

How add item in an object?

I have this in my state:

fbPages:{'123':'Teste','142':'Teste2'}

But I need something like this dynamically:

async getFbPages(){
        var fbPages = {}
            await this.props.resultPosts.facebookPagesList.data.map(item => {
                fbPages.push({item.id: item.name});
            });
            this.setState({fbPages});
            console.log(this.state);
} 

I got a error here fbPages.push({item.id: item.name});, how can I do this?

Upvotes: 2

Views: 15768

Answers (3)

Dev
Dev

Reputation: 3932

Please find below sample snippet:

const items = [{
                id:'123',
                name:'Teste'
               },{
               id: '142',
               name: 'Teste2'
             }];

let fbPages = []; // This should be array.

items.map((item)=> {
    fbPages.push({
       [item.id]: item.name
    })
});

console.log(fbPages);

Upvotes: 1

Nope
Nope

Reputation: 22339

You are using push but fbPages is not an array. If you want to add another property to the object do fbPages[item.id] = item.name; instead

var fbPages = {};
await this.props.resultPosts.facebookPagesList.data.map(item => {
  fbPages[item.id] = item.name;
});

Unless you wanted an array to begin with, then declare it as such instead var fbPages = []

var fbPages = [];
await this.props.resultPosts.facebookPagesList.data.map(item => {
  fbPages.push({
    item.id: item.name
  });
});

Upvotes: 3

Nisarg Thakkar
Nisarg Thakkar

Reputation: 1547

Object does not support push method you need to define fbPages to array

var fbPages= [];
fbPages[0] ={'123':'Teste','142':'Teste2'}

And in Function

async getFbPages(){
            var fbPages= [];
            await this.props.resultPosts.facebookPagesList.data.map(item => {
                fbPages.push({item.id: item.name});
            });
            this.setState({fbPages});
            console.log(this.state);
} 

Upvotes: 0

Related Questions