简体   繁体   English

JavaScript:将对象转换为对象数组

[英]JavaScript: convert objects to array of objects

I have thousands of legacy code that stores array information in a non array. 我有数以千计的遗留代码,用于将数组信息存储在非数组中。

For example: 例如:

container.object1 = someobject;
container.object2 = someotherobject;
container.object3 = anotherone;

What I want to have is: 我想要的是:

container.objects[1], container.objects[2], container.objects[3] etc.

The 'object' part of the name is constant. 名称的“对象”部分是不变的。 The number part is the position it should be in the array. 数字部分是它应该在数组中的位置。

How do I do this? 我该怎么做呢?

Assuming that object1, object2, etc... are sequential (like an array), then you can just iterate through the container object and find all the sequential objectN properties that exist and add them to an array and stop the loop when one is missing. 假设object1,object2等是顺序的(如数组),那么你可以遍历容器对象并找到所有存在的顺序objectN属性并将它们添加到数组中并在缺少一个循环时停止循环。

container.objects = [];  // init empty array
var i = 1;
while (container["object" + i]) {
    container.objects.push(container["object" + i]);
    i++;
}

If you want the first item object1 to be in the [1] spot instead of the more typical [0] spot in the array, then you need to put an empty object into the array's zeroth slot to start with since your example doesn't have an object0 item. 如果你想让第一个项目object1[1]点而不是数组中更典型的[0]点,那么你需要将一个空对象放入数组的第0个插槽中以开始,因为你的例子没有有一个object0项目。

container.objects = [{}];  // init array with first item empty as an empty object
var i = 1;
while (container["object" + i]) {
    container.objects.push(container["object" + i]);
    i++;
}

An alternate way to do this is by using keys . 另一种方法是使用keys

var unsorted = objectwithobjects;
var keys = Object.keys(unsorted);
var items = [];
for (var j=0; j < keys.length; j++) {
  items[j] = unsorted[keys[j]];
}

You can add an if-statement to check if a key contains 'object' and only add an element to your entry in that case (if 'objectwithobjects' contains other keys you don't want). 您可以添加一个if语句来检查一个键是否包含'object',并且在这种情况下只向您的条目添加一个元素(如果'objectwithobjects'包含您不想要的其他键)。

That is pretty easy: 这很简单:

var c = { objects: [] };

for (var o in container) {
    var n = o.match(/^object(\d+)$/);
    if (n) c.objects[n[1]] = container[o];
}

Now c is your new container object, where c.object[1] == container.object1 现在c是你的新容器对象,其中c.object[1] == container.object1

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

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