Javascript: Add object within an object array

Asked

Viewed 635 times

0

I have:

var options = {
    title: 'Titulo',
    width: largura,
    height: altura,
    vAxis: {
        title:"Porcentagem % em vendas",
        format: 'decimal'
    },
    hAxis: {
        title: "Seleção de clientes - Comutativa",
    }
}

However after some time, in order to generate a new view, I need to move to the variable options the following value:

vAxis:{
    ticks:[0,10,20,30,40,50,60,70,80,90,100]
}

but do not know the correct operator to give a push in options, because many times I don’t know what’s inside options then I need add up(+=) inside the object vAxis

  • 1

    I’m not sure I understood the doubt, it would be options.vAxis.ticks = [0,10,20,30,40,50,60,70,80,90,100] ?

  • That’s right, I’m so used to using push and += that sometimes I forget to try the simple, but I don’t understand, how can it assign a value to a variable that doesn’t exist? your answer is right, would be happy to mark it as correct

1 answer

0


That’s what you’re looking for?

var largura = 15;
var altura = 25;
var options = {
    title: 'Titulo',
    width: largura,
    height: altura,
    vAxis: {
        title:"Porcentagem % em vendas",
        format: 'decimal'
    },
    hAxis: {
        title: "Seleção de clientes - Comutativa",
    }
}

console.log(options);

var nOptions = Object.assign({}, options, {
        vAxis: Object.assign({}, options.vAxis, { 
            ticks: [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
        }) 
    });

console.log(nOptions);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.