将对象的属性和值转换为键值对的数组 [英] 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屋!