简体   繁体   English

将javascript关联数组转换为多对象数组

[英]convert javascript Associative Array to multi object array

here is my input: 这是我的输入:

where input may receive more data like 'e:5' 输入可能会收到更多数据,例如'e:5'

  var input = {a:2,b:3,c:2,d:1};

I want to convert this input into below output: 我想将此输入转换为以下输出:

var output = [{name="a",id="2"},
              {name="b",id="3"},
              {name="c",id="2"},
              {name="d",id="1"}];

thanks in advance. 提前致谢。

Use Array#map over Object.keys Object.keys使用Array#map

The Object.keys() method returns an array of a given object's own enumerable properties. Object.keys()方法返回给定对象自己的可枚举属性的数组。


The map() method creates a new array with the results of calling a provided function on every element in this array. map()方法创建一个新数组,并对该数组中的每个元素调用提供的函数。


 var input = { a: 2, b: 3, c: 2, d: 1 }; var mapped = Object.keys(input).map(function(key) { return { name: key, id: input[key] }; }); console.log(mapped); 

Use can Array#forEach over Object.keys Object.keys上可以使用Array#forEach

 var input = {a:2,b:3,c:2,d:1}; var output = []; Object.keys(input).forEach(function(key){ output.push({name:key,id:input[key]}); }) console.log(output); 

Javascript object properties are unordered. Javascript对象属性是无序的。 Because of that, the order of keys returned from Object.keys is undetermined. 因此,不确定从Object.keys返回的键顺序。 In order to maintain the alphabetical order like your example, you need to previously sort the keys , then use map to create a new array with the expected value. 为了像您的示例一样保持字母顺序,您需要预先sort键进行sort ,然后使用map创建具有期望值的新数组。

I don't like ES5. 我不喜欢ES5。 So here is my ES6 answer. 这是我的ES6答案。

Object.keys(input).sort((a, b) => a.localeCompare(b)).map(name => ({name, id: input[name]}));

Just for some fun and for training purposes we may come up with this. 只是出于娱乐和培训目的,我们可能会提出这个建议。 Remember that while it's possible to add later, you can always embed a Symbol.iterator method by the constructor function at the time of instantiation and your objects become iterable by default. 请记住,尽管以后可以添加,但是您始终可以在实例化时通过构造函数嵌入Symbol.iterator方法,并且默认情况下您的对象变得可迭代。

 var input = {a:2,b:3,c:2,d:1}, output = []; input[Symbol.iterator] = function*(){ var ok = Object.keys(this), i = 0; while (i < ok.length) yield {[ok[i]]: this[ok[i++]]}; }; for (var keyValuePair of input) output.push(keyValuePair); console.log(output); // or you can even do like output.length = 0; output = [...input]; // cool console.log(output); 

You can also try below approach : 您也可以尝试以下方法:

var input = {a:2,b:3,c:2,d:1};

var output = Object.keys(input).reduce(function(p, c){
     return p.concat({name:c, id:input[c]});
}, []);

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

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