比较同一数组的当前版本和先前版本以更改javascript中的值

时间:2018-11-28 07:30:14

标签: javascript arrays node.js

我有以下数据数组:

[{"name":"joseph","time":"0","status":"Idle"}] //there are multiple objects inside the array

此对象数组是由节点js服务每秒生成的。我想将新创建的数组与先前创建的数组进行比较,以检查状态的变化。

例如

案例1

newly created 
[{"name":"joseph","time":"0","status":"Idle"}]

previously created
[{"name":"joseph","time":"0","status":"Idle"}]

比较新旧对象的状态:状态不变

案例2

newly created 
[{"name":"joseph","time":"0","status":"Calling"}]

previously created

[{"name":"joseph","time":"0","status":"Idle"}]

比较新旧对象的状态:状态已更改

我希望你明白这一点。 如果状态已更改,则将当前时间分配给时间键。 我无法弄清楚如何保存先前的数组并将其与新创建的数组进行比较。

到目前为止我所做的:

newarray = [{"name":"joseph","time":"0","status":"Calling"}];
previousarray = newarray;
for(i=0;i<=newarray.length;i++){
  for(j=0;j<previousarray.length;j++){
if(previousarray[j].status != newarray[i].status){

  newarray[i].time = moment().format('H:mm:ss');
}
  }
}

但这不起作用。我收到如下错误: TypeError:无法读取未定义的属性“状态”

我该怎么做?

3 个答案:

答案 0 :(得分:1)

首先,您的server <- function(input, output) { #selected data selectedData <- reactive({ data %>% filter(Indicator == input$indicator) }) #map data mapData <- reactive({ left_join(poly, selectedData()) }) output$ggplot_id <- renderPlot({ ggplot(data = mapData()) + ... #further definitions for your plot }) } 是使用previousArraynewArray的引用

改为使用传播运算符语法:

=

然后在第一个循环中,您有const previousArray = [...newArray];而不是<=

<

答案 1 :(得分:0)

可以通过以下可能的方式进行。假设newly_createdpreviously_created

newly_created  = [{"name":"joseph","time":"0","status":"Calling"}, {"name":"joseph - 2","time":"0","status":"Idle"}, {"name":"joseph - 3","time":"0","status":"Calling"}];

previously_created = [{"name":"joseph","time":"0","status":"Idle"}, {"name":"joseph - 2","time":"0","status":"Calling"},  {"name":"joseph - 3","time":"0","status":"Calling"}];


newly_created.forEach(function(newArrObj, index){
	
	if(newArrObj.status !== previously_created[index].status){
		// newArrObj.time = moment().format('H:mm:ss');
              newArrObj.time = new Date().toTimeString().split(' ')[0];
	}
});

console.log('New Array  : ', newly_created);

答案 2 :(得分:0)

我认为您想做这样的事情:

newarray = {"name":"joseph","time":"0","status":"Calling"};
previousarray = newarray;
if(previousarray['status'] !== newarray['status']){

  newarray['time'] = "date-time";

}