17

I have an array of objects. How do I add an id key to them starting from 1.

[
{
    color: "red",
    value: "#f00"
},
{
    color: "green",
    value: "#0f0"
},
{
    color: "blue",
    value: "#00f"
},
{
    color: "cyan",
    value: "#0ff"
},
{
    color: "magenta",
    value: "#f0f"
},
{
    color: "yellow",
    value: "#ff0"
},
{
    color: "black",
    value: "#000"
}
]

So, it will be like

[
{
    color: "red",
    value: "#f00",
    id: 1
},
{
    color: "green",
    value: "#0f0",
    id: 2
},
{
    color: "blue",
    value: "#00f",
    id: 3
},
{
    color: "cyan",
    value: "#0ff",
    id: 4
},
{
    color: "magenta",
    value: "#f0f",
    id: 5 
},
{
    color: "yellow",
    value: "#ff0",
    id: 6
},
{
    color: "black",
    value: "#000",
    id: 7
}
]

I tried using forEach but it was returning the id as the length - 1 value for all the objects inside the array.

I have a large number of objects and can use lodash too.

bad_coder
  • 11,289
  • 20
  • 44
  • 72
arunmmanoharan
  • 2,535
  • 2
  • 29
  • 60

9 Answers9

18

You could use Array#forEach for this. The second argument of the callback refers to the index of the element. So you can assign the ID as index + 1.

const source = [{
    color: "red",
    value: "#f00"
  },
  {
    color: "green",
    value: "#0f0"
  },
  {
    color: "blue",
    value: "#00f"
  },
  {
    color: "cyan",
    value: "#0ff"
  },
  {
    color: "magenta",
    value: "#f0f"
  },
  {
    color: "yellow",
    value: "#ff0"
  },
  {
    color: "black",
    value: "#000"
  }
];

source.forEach((item, i) => {
  item.id = i + 1;
});

console.log(source);
31piy
  • 23,323
  • 6
  • 47
  • 67
  • no, you need to use map function – malininss Apr 17 '23 at 14:45
  • @malininss why do you think so? Using forEach is perfectly valid in this scenario where OP is just asking to add a key to the objects. Using map is just an overkill. – 31piy Apr 18 '23 at 03:38
  • Perhaps I was too critical. While forEach is suitable for changing an object's property by reference, the map function is specifically designed for modifying and returning a new array. Using map is more intuitive, but forEach doesn't allocate additional memory for a new array. The main disadvantage of map is the extra memory required for a new object. However, it's generally better to adhere to immutability unless the object has an extra large number of fields and use the map function for these cases. – malininss Apr 19 '23 at 04:40
12

The simples solution would be to use map function

let data = [{ color: "red", value: "#f00" }, { color: "green", value: "#0f0" }]  

data = data.map((item, index) => ({ ...item, id: index + 1 }))

console.log(data)
Maciej Kozieja
  • 1,812
  • 1
  • 13
  • 32
6

You can use .forEach() to iterate over array elements and add id:

data.forEach((o, i) => o.id = i + 1);

Demo:

let data = [{
    color: "red",
    value: "#f00"
}, {
    color: "green",
    value: "#0f0"
}, {
    color: "blue",
    value: "#00f"
}, {
    color: "cyan",
    value: "#0ff"
}, {
    color: "magenta",
    value: "#f0f"
}, {
    color: "yellow",
    value: "#ff0"
}, {
    color: "black",
    value: "#000"
}];

data.forEach((o, i) => o.id = i + 1);

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
4

You can use the map() function to iterate over your array of objects.

n is each of your objects and you can set the id value inside the map.

Hope this helps :)

let arr = [{
    color: "red",
    value: "#f00"
  },
  {
    color: "green",
    value: "#0f0"
  },
  {
    color: "blue",
    value: "#00f"
  },
  {
    color: "cyan",
    value: "#0ff"
  },
  {
    color: "magenta",
    value: "#f0f"
  },
  {
    color: "yellow",
    value: "#ff0"
  },
  {
    color: "black",
    value: "#000"
  }
]

let i = 0;
arr.map(n => {
  n['id'] = i;
  i++;
})

  console.log(arr);
Gerardo BLANCO
  • 5,590
  • 1
  • 16
  • 35
2
  source.map((s, i)=> s.id = i+1); 
   console.log(source)
Naim Blg
  • 131
  • 1
  • 3
  • 12
  • 5
    Please include a textual explanation of how this solves the problem in the question. It is best to void posting "code only" answers. – bad_coder Aug 13 '20 at 02:05
1

ES6

You can use forEach() to get the required result.

const arr =[{color: "red",value: "#f00"},{color: "green",value: "#0f0"},{color: "blue",value: "#00f"},{color: "cyan",value: "#0ff"},{color: "magenta",value: "#f0f"},{color: "yellow",value: "#ff0"},{color: "black",value: "#000"}];

arr.forEach((o,i)=>o.id=i+1);
console.log(arr);
.as-console-wrapper {max-height: 100% !important;top: 0;}

You can also use map() to get the required result.

DEMO

const arr =[{color: "red",value: "#f00"},{color: "green",value: "#0f0"},{color: "blue",value: "#00f"},{color: "cyan",value: "#0ff"},{color: "magenta",value: "#f0f"},{color: "yellow",value: "#ff0"},{color: "black",value: "#000"}];


console.log(arr.map((o,i)=>Object.assign(o,{id:i+1})));
.as-console-wrapper {max-height: 100% !important;top: 0;}
Community
  • 1
  • 1
Narendra Jadhav
  • 10,052
  • 15
  • 33
  • 44
1

No need for complex function and logic. Simply loop it over forEach which will also give you the index of each object in the array and assign that index+1 value to the id property of the object.

var arr = [
{
    color: "red",
    value: "#f00"
},
{
    color: "green",
    value: "#0f0"
},
{
    color: "blue",
    value: "#00f"
},
{
    color: "cyan",
    value: "#0ff"
},
{
    color: "magenta",
    value: "#f0f"
},
{
    color: "yellow",
    value: "#ff0"
},
{
    color: "black",
    value: "#000"
}
];

arr.forEach((item, index)=>{
 item.id = index+1;
});
console.log(arr);
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
0

when i use this solutions my ids get one number like this:

list = [ {
    color: "red",
    value: "#f00",
    id: 0
}, {

    color: "green",
    value: "#0f0",
    id: 4
},{
    color: "blue",
    value: "#00f",
    id: 4
},{
    color: "cyan",
    value: "#0ff",
    id: 4
},{
    color: "black",
    value: "#000",
    id: 4
}] 

my code is this:

let i = 0;
list.map(n => {
        n['id'] = i;
        i++;
});
Ehsan
  • 308
  • 6
  • 17
0

You can use filter() to remove duplicate and reduce() to achieve the desired output.

const colorArray = [
    {
        color: "red",
        value: "#f00"
    },
    {
        color: "green",
        value: "#0f0"
    },
    {
        color: "blue",
        value: "#00f"
    },
    {
        color: "cyan",
        value: "#0ff"
    },
    {
        color: "magenta",
        value: "#f0f"
    },
    {
        color: "yellow",
        value: "#ff0"
    },
    {
        color: "black",
        value: "#000"
    }
]

const result = colorArray
    .filter((a, i, x) => x.findIndex((t) => t.color === a.color) === i)
    .reduce((agg, item, index) => {
        item.id = index + 1;
        agg.push(item);
        return agg;
    }, []);

console.log(result);
Ashok Kumar
  • 326
  • 2
  • 8