1

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.

4
  • Is it one extra variable you need in the array, or with each value of the array and extra variable? Commented Oct 30, 2014 at 10:47
  • 1
    Your first approach is correct: jsfiddle.net/5v5nky9v Commented Oct 30, 2014 at 10:48
  • 2
    this 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"] Commented Oct 30, 2014 at 10:48
  • 2
    "did not quite work as I intended"? What happened? Commented Oct 30, 2014 at 10:51

2 Answers 2

1
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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.