JavaScript:在不使用reduce库的情况下展平数组 [英] JavaScript: flatten an array without using reduce library

查看:79
本文介绍了JavaScript:在不使用reduce库的情况下展平数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为$ scope.instruments的嵌套数组,其内容为:

I have a nested array named $scope.instruments, its contents are:

折叠:

展开:

我还有一个对象:

该对象包含2个数组:AttributeID和SPAttributeRefID.

This object contains 2 arrays: AttributeID and SPAttributeRefID.

当前,我使用reduce函数将$ scope.instruments数组展平:

Currently I am flattening the $scope.instruments array using reduce function:

$scope.instruments = $scope.instruments.reduce(function (result, instrument) {
    result[instrument.ID] = instrument;
    return result
}, {});

然后我访问对象的AttributeID并将其分配给这样的变量:

Then I access the AttributeID of the object and assign it to a variable like this:

$scope.recordInstrument = $scope.instruments[data.AttributeID[0]].ID;

我宁愿使用其他方法来获得相同的结果.我读到可以使用for循环将数组弄平,这是一种更有效的方法.不幸的是,到目前为止,我所做的尝试并未给我相同的结果.

I would rather use a different method to obtain the same result. I read that an array can be flatten using a for loop, that it is a more efficient method of doing it. Unfortunately, what I have tried so far, is not giving me the same results.

var arrInstruments = $scope.instruments;
var arrLength = arrInstruments.length;

for (var i = 0; i < arrLength; i++) {
    console.log(arrInstruments[i]);                                
}

有人可以帮我转换使用reduce函数的代码以使用循环,并在分配AttributeID时得到相同的结果吗?

Can someone give me a hand converting the code that uses the reduce function to use a loop and have the same result in the assignment of AttributeID?

非常感谢.

推荐答案

此代码应满足您的需求:

This code should do what you are looking for:

var arrInstruments = $scope.instruments;
var arrLength = arrInstruments.length;
var result = {}
for (var i = 0; i < arrLength; i++) {
    result[arrInstruments[i].ID] = arrInstruments[i];
}
// the result variable contains what you want.

但是我真的不明白你为什么要这么做.

However I really don't understand why you would want that.

您拍摄的此屏幕截图:

This screenshot you took:

不是不是多维数组.这只是您的控制台向您显示一个非常大的数组的方式(因此它无需绘制"所有内容).

Is not a multidimensional array. It's only the way your console show you a very large array (so it will not need to "draw" everything).

这篇关于JavaScript:在不使用reduce库的情况下展平数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆