繁体   English   中英

在Javascript中将对象修改为新的数组

[英]Modify an object to a new Array in Javascript

抱歉,ima javascript初学者。 有人可以向我解释如何修改此对象

{toto:[12,13,15],titi:[45,12,34]}

到这个数组

 newArray =  [
 {
  toto:12,
  titi:45
 },{
  toto:13,
  titi:12
 },{
  toto:15,
  titi:34}
]

另外,如果toto和titi的长度不同,该怎么办?谢谢支持!

假设tototiti长度相同:

Obj = {toto:[12,13,15],titi:[45,12,34]};
newArray = [];
for (var k in Obj["toto"]) {
    newArray.push({ toto:Obj["toto"][k],titi:Obj["titi"][k] });
}

由于内部数组的长度相等,因此您应该能够简单地循环遍历它们,并将每个数组的值(每次迭代)添加到新数组中:

// Your input
var input = {toto:[12,13,15],titi:[45,12,34]};
// An array to store your output
var output = [];

// Since your inner arrays are of equal size, you can loop through them
// as follows
for(var i = 0; i < input.toto.length; i++){
    output.push({ toto: input.toto[i], titi: input.titi[i]});
}

您可以在这里看到一个可行的示例,output数组如下所示:

在此处输入图片说明

这是我的方法。 这样,您不需要知道键的名称或数组的大小,但是它确实需要几个循环。

obj = {toto:[12,13,15],titi:[45,12,34]};
newArray = [];

// Find the longest array in your data set
longest = 0;
Object.keys(obj).forEach(function(key) {
  if (obj[key].length > longest) {
    longest = obj[key].length;
  }
});

// Loop through the existing data set to create new objects
for (i = 0; i<longest; i++) {
  newObject = {};
  Object.keys(obj).forEach(function(key) {
    newObject[key] = obj[key][i];
  });
  newArray.push(newObject);
}

console.log(newArray);

script.js文件中的plnkr.co演示

如果要忽略对于不均匀循环可能具有undefined值的键,则可以在forEach循环内添加一个条件来创建新对象:

  Object.keys(obj).forEach(function(key) {
    if (obj[key][i] !== undefined) {
      newObject[key] = obj[key][i];
    }
  });

更通用的方法

 var object = { toto: [12, 13, 15], titi: [45, 12, 34] }, newArray = function (o) { var keys = Object.keys(o), l = keys.reduce(function (r, a) { return Math.max(r, o[a].length); }, 0), i = 0, t, result = []; while (i < l) { t = {}; keys.forEach(function (k) { t[k] = o[k][i]; }); result.push(t); i++; } return result; }(object); document.write('<pre>' + JSON.stringify(newArray, 0, 4) + '</pre>'); 

暂无
暂无

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

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