javascript 如何将数组转换为json对象?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31398984/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to convert Array into json object?
提问by Shrinivas Pai
Dynamically I am getting an array
.
我动态地得到一个array
.
For example we can consider this following array
.
例如,我们可以考虑如下array
。
var sampleArray=[
"logo",
"Details",
"titles"
];
But I want it something like this.
但我想要这样的东西。
jsonObj={
"poistion1":"logo",
"poistion2":"Details",
"poistion3":"titles"
}
采纳答案by Nikhil Aggarwal
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];
}
回答by Alexander T.
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);
回答by Arun P Johny
You can create an empty object, then loop over(Array.forEach()) the array and assign the value
您可以创建一个空对象,然后循环遍历(Array.forEach())数组并分配值
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 -->
回答by Nikhil Batra
var arr=[
"logo",
"Details",
"titles"
];
var result = {};
for (var i = 0; i < arr.length; ++i){
result["position" + (i+1)] = arr[i];
}
回答by Raghavendra
try this
试试这个
var obj = {};
var sampleArray=[
"logo",
"Details",
"titles"
];
for(var index in sampleArray) {
obj['pos' + index] = sampleArray[index];
}
回答by G_hi3
You can use the JSON Object:
您可以使用 JSON 对象:
var yourObject = [123, "Hello World", {name: "Frankie", age: 15}];
var yourString = JSON.stringify(yourObject); // "[123,"Hello World",{"name":"Frankie","age":15}]"
the JSON object has also JSON-to-Object functionality:
JSON 对象还具有 JSON-to-Object 功能:
var anotherObject = JSON.parse(yourString);
var anotherObject = JSON.parse(yourString);