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

杀马特。学长 韩版系。学妹 提交于 2019-11-26 18:15:58

问题


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'

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.

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

回答1:


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.




回答2:


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

You can then join the array for your final string.




回答3:


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.




回答4:


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




回答5:


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>



回答6:


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

:



来源:https://stackoverflow.com/questions/14615669/convert-objects-properties-and-values-to-array-of-key-value-pairs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!