简体   繁体   中英

Easiest way to create a string from an array of objects

Note: ES6 Is welcome, as is loash solutions.

So I have an array, that will only every have two objects of key: value

For example:

[{a: 1}, {b: 2}]

I cannot figure out a solution where it can become: a_1_b_2 as a string.

You cannot assume the key or the value, so you cannot do something like:

let obj = _.merge({}, ...arr);
return `a_${obj.a}_b_${obj.b}`;

Because the key's can be any string and the value can be any number. The object's in the array will only ever have one key and one value and there will only ever be two objects in the array.

With this in mind, how do I create the desired string?

  • Map the array using Object.entries()
  • Flatten to a single array using Array.flat() (2 is the number of levels to flattern, use Infinity for unknown number of levels)
  • Join the items to a string

 const data = [{a: 1}, {b: 2}]; const result = data.map(Object.entries).flat(2).join('_'); console.log(result); 

Here's a solution in lodash that uses a combination of lodash#flatMapDeep and lodash#toPairs to get an array of keys and values that we can join using lodash#join .

 var array = [{a: 1}, {b: 2}]; var result = _(array).flatMapDeep(_.toPairs).join('_'); console.log(result); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script> 

我将通过以下方式解决此问题:

obj.map(x => Object.keys(x) + '_' + Object.values(x)).join('_');
let obj = _.merge({}, ...arr);

obj.map(o => {
   var key = Object.keys(o)[0];
   return `${key}_${o[key]}`;
})
.reduce((a, b) => `${a}_${b}`);

As the others statet you can use map and Object.keys for this job.

Working example: http://jsbin.com/rofufibemu/edit?console

const arr = [{a: "foo"}, {b: 1}, {c: "bar"}];
const str = arr.map(item => {
  return Object.keys(item).map(prop => {
    return prop + "_" + item[prop];
  }).join("__");
}).join("___");

console.log(str);

The code can be reduced by using template strings, never thought of having such problems typing code on a mobile keyboard ;-)

Everyone else is making this overly complicated and obfuscated IMO. Since you can specify exactly the schema of the array to be stringified, you can just build a simple function around that.

 let foo = [{a: 1}, {b: 2}]; function stringify(arr){ let k1 = Object.keys(arr[0])[0]; let v1 = arr[0][k1]; let k2 = Object.keys(arr[1])[0]; let v2 = arr[1][k2]; return `${k1}_${v1}_${k2}_${v2}`; } console.log(stringify(foo)); // a_1_b_2 

This isn't Code Golf - the shortest, most clever, most "elegant" solution is not necessarily always the best one to use. Good luck looking at some of the other solutions 6 months from now and trying to quickly and easily decipher what the function is doing at a glance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM