Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Array into json object? [duplicate]

Dynamically I am getting an array.

For example we can consider this following array.

var sampleArray=[
        "logo",
        "Details",
        "titles"
    ];

But I want it something like this.

jsonObj={
"poistion1":"logo",
"poistion2":"Details",
"poistion3":"titles"
}
like image 260
Shrinivas Pai Avatar asked Jul 14 '15 06:07

Shrinivas Pai


2 Answers

You can iterate on array and create object like following

var jsonObj = {};
for (var i = 0 ; i < sampleArray.length; i++) {
    jsonObj["position" + (i+1)] = sampleArray[i];
}
like image 95
Nikhil Aggarwal Avatar answered Sep 21 '22 23:09

Nikhil Aggarwal


Like this

var jsonObj = {};

var sampleArray = [
    "logo",
    "Details",
    "titles"
];

for (var i = 0, len = sampleArray.length; i < len; i++) {
    jsonObj['position' + (i + 1)] = sampleArray[i];
}

console.log(jsonObj);
like image 36
Oleksandr T. Avatar answered Sep 21 '22 23:09

Oleksandr T.