23

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 + ',';
}
evanmcdonnal
  • 46,131
  • 16
  • 104
  • 115
  • Is there any reason why you aren't using [`JSON.parse()`](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/parse) and [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/stringify)? – NullUserException Jan 30 '13 at 23:17
  • "Going from the key value csl" - What is CSL? – stevebot Jan 30 '13 at 23:18
  • Before this happens I've used `JSON.parse()` to get an object from the json. The problem is in displaying the property names and not just their values. – evanmcdonnal Jan 30 '13 at 23:19
  • @stevebot comma separated list – evanmcdonnal Jan 30 '13 at 23:20
  • @evanmcdonnal: If you have found key-value-csl -> object to be simple, the reverse should be trivial as well? What have you tried, where are you stuck? – Bergi Jan 30 '13 at 23:22
  • @Bergi I have not found they key-value-csl, that was input in a previous session, then written as part an object with in a larger json object. Now I've made an ajax call to get that json and I'm trying to populate the form the way it was when the user originally submitted it. I'll try to add more details to clarify. – evanmcdonnal Jan 30 '13 at 23:24

7 Answers7

41

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.

mojoaxel
  • 1,440
  • 1
  • 14
  • 19
carlosfigueira
  • 85,035
  • 14
  • 131
  • 171
  • If you want to convert your object into a request query then using `jQuery.params` is always recommended over error prone, custom code. – Juzer Ali May 13 '13 at 15:07
5

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

Rashi Abramson
  • 1,127
  • 8
  • 16
4
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.

Plynx
  • 11,341
  • 3
  • 32
  • 33
4
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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • It is guaranteed....just in alphabetical order instead of placed order. – GoldBishop Jan 18 '17 at 17:43
  • @GoldBishop Nope, [it's not](http://stackoverflow.com/q/30076219/1048572). If you want alphabetic order, do `array.sort().join(',')`. – Bergi Jan 18 '17 at 17:53
  • Maybe its happen-stance, but it has been pretty reliable for me without using sort. But i also usually go from Object -> Array -> String or just Object -> String. – GoldBishop Jan 18 '17 at 17:59
  • Yes, it seems to be happen-stance. You cannot rely on it, but most implementations do keep definition order (I haven't heard of an alphabetic one). – Bergi Jan 18 '17 at 18:18
  • Could also be that Chrome applies its own sort when inspecting the various Types. – GoldBishop Jan 18 '17 at 19:13
2

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>
mojoaxel
  • 1,440
  • 1
  • 14
  • 19
2
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

Ram Pukar
  • 1,583
  • 15
  • 17
0

1-liner:

Object.entries(yourObj).map(e => ({ name: e[0], value: e[1] }));

Example use:

let yourObj = { foo: "bar", baz: "bas" };

// turn object properties into array entries
let array = Object.entries(yourObj).map(e => ({ name: e[0], value: e[1] }));

// returns
array = [
  { name: "foo", value: "bar" },
  { name: "baz", value: "bas" },
]
// loop over it
for (let prop of array) {
  console.log(prop.name, "=", prop.value);
}
// shows
foo = bar
baz = bas

Alternatively, create string in the format you wanted:

Object.entries(yourObj).map(e => e[0] + "=" + e[1]).join(",");
"foo=bar,baz=bas"
Ben Bucksch
  • 395
  • 3
  • 13