简体   繁体   English

从对象数组创建字符串的最简单方法

[英]Easiest way to create a string from an array of objects

Note: ES6 Is welcome, as is loash solutions. 注意:欢迎使用ES6,也可以使用Loash解决方案。

So I have an array, that will only every have two objects of key: value 所以我有一个数组,每个数组只有两个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. 我无法找出解决方案可以变成的解决方案: a_1_b_2作为字符串。

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() 使用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) 使用Array.flat()平为单个数组(2是要进行展平的级别数,对于无限多个级别使用Infinity)
  • 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 . 这是lodash中的一种解决方案,它结合使用lodash#flatMapDeeplodash#toPairs来获取键和值的数组,我们可以使用lodash#join进行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. 正如其他人所述,您可以使用map和Object.keys来完成这项工作。

Working example: http://jsbin.com/rofufibemu/edit?console 工作示例: 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. 这不是Code Golf-最短,最聪明,最“优雅”的解决方案不一定总是最好的解决方案。 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. 祝您好运,从现在开始的6个月内,看看其他解决方案,并试图快速,轻松地了解一下该功能的作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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