-1

I have an array which have list of objects and here I need to clone one object which has "id = 1243". Please help me to do this. Thanks.

 list :  [
             {
                 name    : "someName",
                 id      : 1241,
                 value   : 10,
             },                                                  

             {
                 name    : "someName",
                 id      : 1242,
                 value   : 12,

             },

             {
                name    : "someName",
                id      : 1243,
                value   : 15,
             },
             {
                name    : "someName",
                id      : 1244,
                value   : 11,
             }
 ],
prakashstar42
  • 677
  • 1
  • 6
  • 16
  • 2
    Have you tried anything? – Jake Sellers Jul 23 '14 at 05:57
  • ya I am keep searching, but didnt get right solution. – prakashstar42 Jul 23 '14 at 05:58
  • [Combine](https://support.google.com/websearch/answer/134479?hl=en) [this](http://stackoverflow.com/questions/2722159/javascript-how-to-filter-object-array-based-on-attributes) and [this](http://stackoverflow.com/questions/122102/what-is-the-most-efficient-way-to-clone-an-object). – Ram Jul 23 '14 at 06:00

5 Answers5

1

Use grep in jquery to select particular object

          var obj;
            obj= jQuery.grep(list, function( n, i ) {
                  return n.id==1243;
            });

       var copy= JSON.parse(JSON.stringify(obj)); // copy the object

or //var newObject = jQuery.extend(true, {}, obj);`

DEMO

Balachandran
  • 9,567
  • 1
  • 16
  • 26
0

You can iterate over the array with a forEach, compare the Id and copy the object to a variable when matched, or, just use lodash's pluck method.

Jake Sellers
  • 2,350
  • 2
  • 21
  • 40
0

Maybe you can use clone()

Reference: http://api.jquery.com/clone/

Kyle Emmanuel
  • 2,193
  • 1
  • 15
  • 22
0

Try this:

arr.push({
                 name    : "someName",
                 id      : 1241,
                 value   : 10,
             });
arr.push({
                 name    : "someName",
                 id      : 1242,
                 value   : 12,

             });
arr.push({
                name    : "someName",
                id      : 1243,
                value   : 15,
             });
var obj;
for(var i=0;i<arr.length;i++)
{
    var temp = arr[i];
    if(temp.id==1243)
    {
        obj=temp;
    }
}
console.log(obj);//your result

DEMO

Manwal
  • 23,450
  • 12
  • 63
  • 93
0

Demo ,Try this,

var find_id=list[2].id;
console.log(find_id);
hari
  • 1,874
  • 1
  • 16
  • 10