How can I convert an array to json object?

Dynamically I get array

.

For example, we can consider this the following array

.

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

      

But I want something like this.

jsonObj={
"poistion1":"logo",
"poistion2":"Details",
"poistion3":"titles"
}

      

+3


source to share


6 answers


You can iterate over the array and create an object like the following



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

      

+3


source


You can create an empty object then loop over ( Array.forEach () ) the array and assign the value



var sampleArray = [
  "logo",
  "Details",
  "titles"
];
var obj = {};
sampleArray.forEach(function(value, idx) {
  obj['position' + (idx + 1)] = value
});

snippet.log(JSON.stringify(obj))
      

<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
      

Run codeHide result


+3


source


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);
      

Run codeHide result


+3


source


var arr=[
        "logo",
        "Details",
        "titles"
    ];
var result = {};
  for (var i = 0; i < arr.length; ++i){
      result["position" + (i+1)] = arr[i];
 }

      

+2


source


try it

var obj = {};
var sampleArray=[
        "logo",
        "Details",
        "titles"
    ];

for(var index in  sampleArray) {
     obj['pos' + index] = sampleArray[index];
   }

      

0


source


You can use JSON object:

var yourObject = [123, "Hello World", {name: "Frankie", age: 15}];
var yourString = JSON.stringify(yourObject); // "[123,"Hello World",{"name":"Frankie","age":15}]"

      

JSON object has JSON-to-Object functionality as well:

var anotherObject = JSON.parse(yourString);

0


source







All Articles