简体   繁体   中英

How to increment value of object property using javascript?

i have a object named output like below

const output = { 
    count {
        books: 3,
        pens: 2,
        name: 'first',
    }
}

i want to increment the books value by 1, name value to 'second' and leave pens value to be same.

what i have tried?

const books = output.count.books + 1;
const pens = output.count.pens;
const name = 'second';

output = {
    books: books,
    pens: pens,
    name: name,
}

How can i rewrite this code? could soemone help me with this. thanks.

You missed ' : ' in your object after 'count' and also you tried to override 'output' which is a constant.

 const output = { count: {books:3,pens:2,name:'first'} } const books = output.count.books + 1; const pens = output.count.pens; const name = 'second'; let result = { books: books, pens: pens, name: name, } console.log(result);

I would just increment the values of books and update the name:

 const output = { count: {books:3,pens:2,name:'first'} } output.count.books++; output.count.name = 'second'; console.log(output);

try this way

 let output = { count: { books: 3, pens: 2, name: 'first', } } const books = output.count.books + 1; const pens = output.count.pens; let name = output.count.name; name = "second"; output = { 'books': books, 'pens': pens, 'name': name, } console.log(output);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM