简体   繁体   中英

How to push into json array?

var array = ["History"]
...
for (var i = 0; i<div.length; i++){
    var array2 = {
        "name": div[i].value
    };
}
array.push(array2);

I need to create root of array as showing below

"History":{
    0:{
        name: "some text"
    },
    1:{
        name: "some text 2"
    }
}

But in result there is no parent HISTORY as showing below. How can I create child History and into the child push as showing above?

0: "History",
1: {
    name: "some text"
},
2: {
    name: "some text 2"
}

Easy ES6 example.

const tag = 'History';
const obj = {[tag]: {}};
const res = ['ex1', 'ex2', 'ex3'].reduce((acc, x, i) => {acc[tag][i] = x; return acc;}, obj);

console.log(res); // { "History": { 0: "ex1", 1: "ex2", 2: "ex3" } }

Old browser support.

var tag = 'History';
var obj = {History: {}};
var res = ['ex1', 'ex2', 'ex3'].reduce(function(acc, x, i){ acc[tag][i] = x; return acc; }, obj);

console.log(res); // Same output as above

Make the History an element of array object (and give it proper name...). then History can be a root element of array' in it you can use push function:

var array = {"History":[]};
...
array.History.push(array2);

Declare the value of array["History"] as an array and push values into that one:

    var array = ["History"]
    array["History"] = [];
    ...
    for (var i = 0; i<div.length; i++){
        array["History"].push( {
            "name": div[i].value
        });
    }

There is no thing like a "json array" or "json object" . JSON is always text. It is a text representation of a data structure that can be an array or an object. It uses the JavaScript notation for arrays and objects.

In order to get this JSON:

"History":{
    0:{
        name: "some text"
    },
    1:{
        name: "some text 2"
    }
}

you need to build a PHP object or array . PHP arrays are more versatile than bare objects and I recommend you use them.

PHP arrays whose keys are numeric, consecutive and starting from zero are encoded as arrays in JSON. The other arrays are encoded as objects.

This array must have only one key ( "History" ) and its associated value must be an array (numerically indexed) that contains two arrays. Each of these arrays must have only one key: "name" .

Your array would be like this:

$input = array(
    "History" => array(
        array("name" => "some text"),
        array("name" => "some text 2"),
    ),
);

When passed to json_encode() it produces a JSON equivalent to the one you expect.

There are countless ways to build the input array. Read more about accessing and modifying array elements using the square brackets syntax .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM