Javascript 将对象的属性和值转换为键值对数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14615669/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 17:24:36  来源:igfitidea点击:

Convert object's properties and values to array of key value pairs

javascriptreflectionintrospection

提问by evanmcdonnal

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'

我对 JavaScript 相当陌生,不确定这是否可行,但基本上我想获取一个对象并将其转换为格式的字符串数组; array[0] = 'prop1=value1'

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.

这背后的原因是我让用户将 k=v 对的列表输入到一个表单中,后来它被写成一个 json blob 中的对象。从键值 csl 到 json 对象很简单,现在我需要以另一种方式返回(我已经通过 ajax 调用接收到 JSON 并想要填充一个空白表单)。这在 JavaScript 中可能吗?如果没有,请提供合理的解决方法。

Sample code;

示例代码;

Object in debugger;

调试器中的对象;

 Object
        private_key: "private-key"
        public_key: "public-key"

I need to convert that to;

我需要将其转换为;

 "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 + ',';
}

回答by carlosfigueira

You're probably looking for something along the lines of

你可能正在寻找类似的东西

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.

请注意,如果您的值是字符串,它将正常工作;如果它们是复杂的对象,那么您将需要添加更多代码。

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.

或者您可以只使用jQuery.param,它可以满足您的需求,即使对于复杂类型(尽管它使用&字符作为分隔符,而不是逗号。

回答by remydib

In ES6 you can use Object.entries({object1:1,object2:2});. The result is: [["object1",1],["object2",2]]

在 ES6 中,您可以使用Object.entries({object1:1,object2:2});. 结果是:[["object1",1],["object2",2]]

回答by Plynx

var array = [];
for (k in o)
{
    if (o.hasOwnProperty(k))
    {
        array.push(k+"="+o[k]);
    }
}

You can then jointhe array for your final string.

然后你可以join为你的最终字符串数组。

回答by Bergi

var object = {
    private_key: "private-key",
    public_key: "public-key"
};

var array = [];
for (var prop in object)
    array.push(prop + "=" + object[prop]);
return array.join(','); // "private_key=private-key,public_key=public-key"

Notice the order is not guaranteed.

请注意,订单无法保证。

回答by mojoaxel

obj = {
  private_key: "private-key",
  public_key: "public-key"
}

str = JSON.stringify(obj).replace(/[{}]/g, '').replace(/"/g, '').replace(/:/g, '=');
console.log("Using JSON.stringify:\n", str);

str = Object.keys(obj).map((key) => `${key}=${obj[key]}`).join(',')
console.log("Using ES6 keys/map:\n", str);

str = jQuery.param(obj).replace(/&/g,',');
console.log("Using jQuery.param:\n", str);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

回答by Ram Pukar

var obj =[
            {'2018-05-07':1},
            {'2018-05-08':3},
            {'2018-05-09':2}
        ];

        for(var i of obj) {
            var key = Object.keys(i).toString();
            console.log(i,'=',i[key]);
        }

Result

结果

: enter image description here

在此处输入图片说明