admin管理员组文章数量:1325236
key:[id,name,address]
value:[7,John,NewYork]
I wish to create a json data like{"id": 7, "name": "John", "address": "NewYork"}
using for(...){...},
and then return it to ajax
$.ajax({
//what kind of format should json data be here?
data:??json data??,
dataType: 'json',
});
Please help me
key:[id,name,address]
value:[7,John,NewYork]
I wish to create a json data like{"id": 7, "name": "John", "address": "NewYork"}
using for(...){...},
and then return it to ajax
$.ajax({
//what kind of format should json data be here?
data:??json data??,
dataType: 'json',
});
Please help me
Share Improve this question asked Apr 30, 2016 at 14:37 peterpeter 611 silver badge2 bronze badges4 Answers
Reset to default 4To the first part of your question:
You could use Array#forEach()
and assign all properties with the correspondet value.
var key = ['id', 'name', 'address'],
value = [7, 'John', 'New York'],
object = {};
key.forEach(function (k, i) {
object[k] = value[i];
})
document.write('<pre>' + JSON.stringify(object, 0, 4) + '</pre>');
You could:
iterate through both arrays...
...add the 1st array element to an empty obj as a key...
...and assign the 2nd array element to the 1st array element as it's value.
Each iteration will be paired as key/value when stringified as a JSON.
I'm surprised it actually worked, take a look at the demo below:
SNIPPET
var x = ['id', 'name', 'address'];
var y = [7, 'John', 'NewYork'];
function arrMerge(k, v) {
var obj = {};
for (var i = 0; i < k.length; i++) {
obj[k[i]] = v[i];
}
return obj;
}
var z = arrMerge(x, y);
var json = JSON.stringify(z);
console.log(json);
You can write a general function that zips two arrays together into an object if they're of equal length (also assuming they're in the correct order).
function zip(arr1, arr2) {
if (arr1.length !== arr2.length) return false;
const obj = {};
for (let i = 0; i < arr1.length; i++) {
const key = arr1[i];
obj[key] = arr2[i];
}
return obj;
}
zip(arr1, arr2); // { id: 7, name: "John", address: "NewYork" }
DEMO
You can then use that object as the value of data
in your AJAX process.
data
Type: PlainObject or String or Array
Data to be sent to the server. It is converted to a query string, if not already a string.
jQuery documentation
I guess unlike forEach, since it returns the result, Array.prototype.reduce()
es very handy for these operations. You can even use it at the stage of declaring your JSON data (jData
here).
var key = ['id', 'name', 'address'],
value = [7, 'John', 'New York'],
jData = JSON.stringify(key.reduce((p,c,i) => {p[c] = value[i]; return p},{}));
document.write("<pre>" + jData + "</pre>");
本文标签: javascriptHow to create a json data using two arrays and return it to ajaxStack Overflow
版权声明:本文标题:javascript - How to create a json data using two arrays and return it to ajax - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742167228a2426050.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论