将对象的属性和值转换为键值对数组 [英] Convert object's properties and values to array of key value pairs
问题描述
我对 JavaScript 还很陌生,不确定这是否可行,但基本上我想获取一个对象并将其转换为格式的字符串数组;array[0] = 'prop1=value1'
I'm fairly new to JavaScript and am not sure this is possible to do but basically I would like to take an object and convert it into an array of strings in the format; array[0] = 'prop1=value1'
这背后的原因是我让用户将 k=v 对的列表输入到一个表单中,后来它被写成一个 json blob 中的对象.从键值 csl 到 json 对象很简单,现在我需要以另一种方式返回(我已经通过 ajax 调用接收到 JSON 并想要填充一个空白表单).这在 JavaScript 中可行吗?如果没有,请提供合理的解决方法.
The reasoning behind this is that I'm having a user enter a list of k=v pairs into a form, later it's written as an object within a json blob. Going from the key value csl to the json object was simple, now I need to go back the other way (I've received the JSON via an ajax call and want to populate a blank form). Is this possible in JavaScript? If not please offer a reasonable work around.
示例代码;
调试器中的对象;
Object
private_key: "private-key"
public_key: "public-key"
我需要将其转换为;
"private_key=private-key,public_key=public-key"
基本上我需要这样的东西(伪代码)
Basically I need something like this (pseudo code)
var outputString = '';
foreach (prop in obj)
{
outputString = outputString + prop.tostring() + '=' + prop.value + ',';
}
推荐答案
您可能正在寻找类似
var obj = {value1: 'prop1', value2: 'prop2', value3: 'prop3'};
var arr = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
arr.push(key + '=' + obj[key]);
}
};
var result = arr.join(',');
alert(result);
请注意,如果您的值是字符串,它将正常工作;如果它们是复杂的对象,那么您需要添加更多代码.
Notice that it will work fine if your values are strings; if they're complex objects then you'll need to add more code.
或者你可以只使用 jQuery.param,它可以做你想做的事,即使是复杂类型(尽管它使用 &
字符作为分隔符,而不是逗号.
Or you can just use jQuery.param, which does what you want, even for complex types (although it uses the &
character as the separator, instead of the comma.
这篇关于将对象的属性和值转换为键值对数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!