1

I am having the json like this:

{
    json{
        "81":[
            {
            "name":"",
            "id":""
            },
            {
            "name":"",
            "id":""
            }
        ]
    }
}

I am getting this json dynamically and i am storing this json in adlist. I want to insert the element into the array in the third position. i tried like this:

 var temp={"name":"","id":""};
 adlist.json[81].splice(2,0,temp);

But it is not adding the string correctly.

3
  • What error are you seeing? What does adlist look like after you spilce? Commented Oct 29, 2013 at 6:24
  • 1
    It is inserting the new element as one object Commented Oct 29, 2013 at 6:26
  • Your problem is rather about how to process arrays/objects in JavaScript. How you obtained the data (e.g. via JSON) is irrelevant to the problem. Commented Oct 29, 2013 at 6:49

3 Answers 3

2

Try

adlist.81.push({name: "Douglas Adams", id: "comedy"});
Sign up to request clarification or add additional context in comments.

2 Comments

I couldn't see how the json is getting to adlist so I'm not sure of how it is structured. My point was to use .push(). Try adlist.json.81.push({name: "Douglas Adams", id: "comedy"});
No, that's not what I meant. You cannot access numeric properties with dot notation, you have to use bracket notation. That's the reason why you can only access array elements with foo[0] and not with foo.0. I.e. you have to use adlist[81].
1

You can also try this too for better performance,

adlist.json["81"][adlist.json["81"].length]  ={name: "Douglas Adams", id: "comedy"};

1 Comment

@FelixKling Oops, I just wanted to implement amosmos answer in a effective/different way, Forgot to see that and realized the ill effects of copy pasting.
0

It's working for me :)

Java Script Code:

//your json data
var adlist = {json:{"81":[{"name":"first","id":"1"},{"name":"second","id":"2"}]}};

// your new json data
var temp={"name":"Third","id":"3"};

// insert your new json data in 3rd position
adlist.json["81"].push(temp);

// check with console
console.log(adlist);

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.