1

I'm getting this weird error.

    Uncaught SyntaxError: Unexpected token [

I don't know why this error occurs.

Could anyone please tell me why this error occurs and how to solve it?

sortedArray.push({filteredKeys[i]:_analyzedDataSet[filteredKeys[i]]});

This error occurs on this line above.

console.log("filteredKeys[i]:%s", filteredKeys[i]);

However, this line above works fine.

console.log("_analyzedDataSet[filteredKeys[i]]:%s", _analyzedDataSet[filteredKeys[i]]);

Also, this line above works fine.

var filteredKeys = [];

filteredKeys = sortThis(_analyzedDataSet);

var sortedArray = [];
for (var i = 0; i < filteredKeys.length; i++){

    //This doesn't cause an error.
    console.log("filteredKeys[i]:%s", filteredKeys[i]);

    //This doesn't cause an error as well.
    console.log("_analyzedDataSet[filteredKeys[i]]:%s", _analyzedDataSet[filteredKeys[i]]);

    //But, this cause an error!!
    sortedArray.push({filteredKeys[i]:_analyzedDataSet[filteredKeys[i]]});
}
W3Q
  • 909
  • 1
  • 11
  • 19
  • what are you trying to do with that colon in there? – Joe T Sep 07 '14 at 04:52
  • the colon is the divider for key & value.{"key":"value} – W3Q Sep 07 '14 at 04:53
  • See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object "Parameters nameValuePair1, nameValuePair2, ... nameValuePairN Pairs of names **(strings)** and values (any value) where the name is separated from the value by a colon." – guest271314 Sep 07 '14 at 05:09

1 Answers1

4

You can't add dynamic keys to an object when using an object literal notation. Create the object first and add the key using array notation

var newObj = {};
newObj[filteredKeys[i]] = _analyzedDataSet[filteredKeys[i]];
sortedArray.push(newObj);
JeremyWeir
  • 24,118
  • 10
  • 92
  • 107
  • OK! Thanks! I'm going to try it now :) – W3Q Sep 07 '14 at 05:18
  • 1
    >can't add dynamic keys to an object when using an object literal notation I didn't know that. – W3Q Sep 07 '14 at 05:18
  • Yeah, it isn't going to evaluate the key in the object literal for the return value and assign that to the key. It was trying to add a key literally called 'filteredKeys[i]' to the object, but didn't like the square bracket in the identifier. – JeremyWeir Sep 07 '14 at 05:21