开发者

Extract a section of many objects in an array

If I have array of objects like thi开发者_运维问答s

[
    {
        "name" : "some name",
        "more data" : "data",
        ...
    },
    {
        "name" : "another name",
        "more data" : "data",
        ...
    },
    ...
]

And I want to copy the array, but only the name element in the object so that I have this:

[
    {
        "name" : "some name",
    },
    {
        "name" : "another name",
    },
    ...
]

Is there a short hand way to do this without writing a loop?


No, you have to do this with a loop, but in can still be short:

for(var i = 0; i < arr.length; i++)
    arr[i] = {name: arr[i].name};

If you use any sort of framework or library all it will do is hide the loop from you. It will still loop through everything.

Example


No, there is no way of doing this without a loop. Can I suggest you do this with a bit of prototyping magic. (Note, this can be done with some map or forEach magic which just hides away the fact that you're looping. I'll leave this with the loop to illustrate the idea)

Array.prototype.clone = function(predicate)
{
   var newArray = [];
   for(var i = 0;i <this.length; i++){
       var newElement = {};
       for(x in this[i]){
           if(predicate(x)){
              newElement[x] = this[i][x];
          }
       }
      newArray.push(newElement);
   }
    return newArray;
}

This allows you to clone an array, passing in a function that decides which property to keep from each element in the array. So given an array like:

var arr = [
    {
        "name" : "some name",
        "more data" : "data"
    },
    {
        "name" : "another name",
        "more data" : "data"
    }
];

You can do

var newArray = arr.clone(function(x){ return x == "name";});

Which will return you an array with the same number of objects, but each object will just have the name element.

Live example: http://jsfiddle.net/8BGmG/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜