1

May be it is dumb question. I have array object like

var projects = [
        {
            value: "jquery",
            label: "jQuery",
            desc: "the write less, do more, JavaScript library",
            icon: "jquery_32x32.png"
        },
        {
            value: "jquery-ui",
            label: "jQuery UI",
            desc: "the official user interface library for jQuery",
            icon: "jqueryui_32x32.png"
        },
        {
            value: "sizzlejs",
            label: "Sizzle JS",
            desc: "a pure-JavaScript CSS selector engine",
            icon: "sizzlejs_32x32.png"
        }
    ];

length of 3

I want to add id in all objects like

        {
            id:1
            value: "jquery",
            label: "jQuery",
            desc: "the write less, do more, JavaScript library",
            icon: "jquery_32x32.png"
        },
        {
            id:2
            value: "jquery-ui",
            label: "jQuery UI",
            desc: "the official user interface library for jQuery",
            icon: "jqueryui_32x32.png"
        },
        {
            id:3
            value: "sizzlejs",
            label: "Sizzle JS",
            desc: "a pure-JavaScript CSS selector engine",
            icon: "sizzlejs_32x32.png"
        }

How can i do that?

3 Answers 3

3

You can do it by using Array.prototype.map(),

projects = projects.map(function(itm,i){
 return (itm.id = i+1, itm);
});

DEMO

If you don't want to use functional programming, then you can use a simple for loop for this purpose no need for "forEach",

for(var i=0,len=projects.length; i<len; i++){
  projects[i].id = i+1;
}
Sign up to request clarification or add additional context in comments.

2 Comments

It's a bit odd cloning the array for no reason, in a way that mutates the original objects anyway.
@Emissary Let OP know about that(map) also. It would be handy for him in other occasions. Also I have provided a solution for the problem that you are saying by a simple for loop.
2

No need for Array#map, because the access is direct possible with itm as object.

projects.forEach(function(itm, i) {
   itm.id = i + 1;
});

1 Comment

but forEach method doesn't return anything
0

If care about speed ) ... "fast" solution with "negative" while loop:

var len = projects.length;
while (len--) {
    projects[len]['id'] = len + 1;
}

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.