I had a question I just couldn't find the answer to. Say I have something like the following:
var test = [{"a": "1", "b": "2", "c": "3", "d": "4"}];
Now, say I wanted this test array to have an additional value based on some predetermined condition. I could do this:
if(cond) {
var test = [{..., "cond": true}];
}
else {
var test = [{...}];
}
In essence, I want the array key to exist if the condition holds.
I tried the following so far:
test[0]["cond"] = true; // (similar to how php does it, I thought)
test[0].push("cond":true");
But they did not quite work as I intended (or at all). How would I achieve the above? It would avoid a lot of code duplication.
-
Is it one extra variable you need in the array, or with each value of the array and extra variable?Martijn de Langh– Martijn de Langh2014年10月30日 10:47:59 +00:00Commented Oct 30, 2014 at 10:47
-
1Your first approach is correct: jsfiddle.net/5v5nky9vAndy– Andy2014年10月30日 10:48:03 +00:00Commented Oct 30, 2014 at 10:48
-
2this is not a 2d array though, it is an array with 1 object inside at the moment, saying that you can still access the objects elemts using test[0]["cond"]Quince– Quince2014年10月30日 10:48:21 +00:00Commented Oct 30, 2014 at 10:48
-
2"did not quite work as I intended"? What happened?Cerbrus– Cerbrus2014年10月30日 10:51:00 +00:00Commented Oct 30, 2014 at 10:51
2 Answers 2
test[0]["cond"] = true;
Should actually work as well as
test[0].cond = true;
Take into consideration that it is not actually a 2D Array, it's an Array of javascript Objects that have different methods than arrays. For instance, javascript Object does not have a push() method.
Comments
A Object is not an Array. You have a Object so you can't use push.
You can use the first method:
var test = [{"a": "1", "b": "2", "c": "3", "d": "4"}];
// Here you condition
if (cond === true) { test[0]["cond"] = true; }
See DEMO