-1

I have an array of JSON-like object[Object,Object...] (I was calling it array of JSON object until I see this ) and I would like to go through each item in it. The JSON object has 3 values {name:"name",date:"2015-01-01",c:3} in it and I want to put each of them into a new array. Should I use a for item in JSONArary{item = ...} or for (i=0,i<len,i++){array[i] = ....} or should I JSONArray.pop()? Which one is faster and why? What if I want to reverse the array? Do reversing cost a lot?

pledez
  • 339
  • 1
  • 4
  • 19
  • 1
    I'm voting to close this question as off-topic because `"premature optimization is the root of all evil"` Did you even check whether this is actually slowing down your application? – royhowie Jun 30 '15 at 03:31

2 Answers2

1

for (i=0,i<len,i++){array[i] = ....} should be faster than for item in JSONArary{item = ...} because the later will traverse all enumerable properties on this object, while some of these properties are unnecessary.

When you want to iterate over just the indexed properties of an array, the only guaranteed way to keep things semantically consistent is to use an integer index.

For your reference: Why is using "for...in" with array iteration a bad idea?

Even Google make the JavaScript coding style guide as:

for-in loop: Only for iterating over keys in an object/map/hash

Community
  • 1
  • 1
Joy
  • 9,430
  • 11
  • 44
  • 95
0

I have a faster way, use $.map:

var oldArray = [{
    name: "name1",
    date: "2015-01-01",
    c: 3
}, {
    name: "name2",
    date: "2015-01-01",
    c: 3
}, {
    name: "name3",
    date: "2015-01-01",
    c: 3
}];
var newArray = $.map(oldArray, function (item) {
    return {
        FullName: item.name,
        RegisterDate: item.date
    };
});
alert(JSON.stringify(newArray));

Hope this help.

hungndv
  • 2,121
  • 2
  • 19
  • 20
  • 2
    Because loading in an entire library is faster… [`Array.prototype.map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) – royhowie Jun 30 '15 at 03:33