简体   繁体   English

从JavaScript中的数组动态获取对象

[英]Get objects from array in javascript dynamically

I have below code 我有下面的代码

var obj = [];
var statuses = [];
var time ='';

statuses array has some values like 
statuses[0] = [1]
statuses[1] = [0]
statuses[2] = [1]
statuses[3] = [1]

Now i want to push these values in obj array such that when i do obj[0].length it should come to 5 现在,我想将这些值推送到obj数组中,这样当我执行obj [0] .length时它应该变为5

If i do obj.push(([time, statuses])) it gives length as 2 如果我做obj.push(([[time,statuses])))它给出的长度为2

When i do obj.push(([time, statuses[0],statuses[1],statuses[2],statuses[3]])); 当我做obj.push(([time, statuses[0],statuses[1],statuses[2],statuses[3]])); then i am getting value of obj[0].length as 5 然后我得到obj [0] .length的值为5

I dont want to hardcode the values like statuses[0],[1] in obj.push as i am not sure how many values will be present in statuses array in future. 我不想在obj.push中对诸如statuss [0],[1]之类的值进行硬编码,因为我不确定将来在statuss数组中会出现多少个值。

Ofcourse my status array will grow depending upon the values i receive from backend. 当然,我的状态数组将根据我从后端收到的值而增长。 So my obj[0].length should be number of objects in status array + time obj. 因此,我的obj [0] .length应该是状态数组中的对象数+时间obj。 Eg: if statuses has 8 values then my final obj[0].length should come to 9 例如:如果状态具有8个值,则我的最终obj [0] .length应该为9

I have tried using concat function but their is no luck. 我已经尝试过使用concat函数,但运气不佳。

Could anyone please help me out with how can I achieve this dynamically? 谁能帮我解决如何动态实现这一目标?

Try this: 尝试这个:

var temp = [];
temp.push(time);
foreach(function(s, i, statuses) {
    temp.push(s);
});
obj.push(temp);

If I understand you correctly you should push your elements to first element of obj array 如果我理解正确,则应将元素推到obj数组的第一个元素

var obj = [[]];
var statuses = [];
var time ='';

statuses array has some values like 
statuses[0] = [1];
statuses[1] = [0];
statuses[2] = [1];
statuses[3] = [1];

// === SOLUTION ===

obj[0].push(time);
for(var i; i<statuses.length;i++)
{
   obj[0].push(statuses[i]);
}

EDIT : Answer to another question in comment Always try to draw and visualize how your arrays could look like when you populate its in your requested way. 编辑 :回答评论中的另一个问题始终尝试绘制并可视化以请求的方式填充数组时的外观。

var obj = [];
var statuses = [];
var time ='';

for(var k=0;k<12;k++)
{
    statuses[0] = [1];
    statuses[1] = [0];
    statuses[2] = [1];
    statuses[3] = [1];

    // === SOLUTION ===

    obj.push([]);
    obj[k].push(time);
    for(var i; i<statuses.length;i++)
    {
       obj[k].push(statuses[i]);
    }
}

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

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