[英]How to copy an array of JSON objects in javascript
I have an array of objects in JavaScript. 我在JavaScript中有一组对象。 eg
current_films[0].f_name, current_films[0].f_pattern
etc. I want to copy the array into another similiar to the following: 例如
current_films[0].f_name, current_films[0].f_pattern
等。我想将数组复制到另一个current_films[0].f_name, current_films[0].f_pattern
以下的数组:
for(var i=0; i<current_films.length; i++)
{
if(current_films[i].f_material == Value)
{
temp[i] = current_films[i];
}
}
However, there seems to be an inexplicable problem when I do this. 但是,当我这样做时,似乎有一个莫名其妙的问题。 By inexplicable problem, I mean that the code does not execute and the array is not copied as I desire.
由于莫名其妙的问题,我的意思是代码没有执行,数组也没有按照我的意愿复制。
Any help would be greatly appreciated. 任何帮助将不胜感激。 Thank you!
谢谢!
PS Could you please mention why the above code would not work? 你能否提一下为什么上面的代码不起作用? As in, if I put an
alert("Reached here");
就像在,如果我发出
alert("Reached here");
, it's not getting executed. ,它没有被执行。 Any ideas why its so?
任何想法为何如此?
One problem I see is that you set temp[i]
to the value which means there would be gaps in the temp
array. 我看到的一个问题是你将
temp[i]
设置为值,这意味着temp
数组中会有间隙。 You could use push()
to append the value to temp
so you don't need to manage two sets of indices. 您可以使用
push()
将值附加到temp
这样您就不需要管理两组索引。
You could also use JavaScript's Array.filter()
to do this a little easier. 你也可以使用
JavaScript's Array.filter()
来做到这一点。 Filter will return a new array of the values from the original array where your function returns true
. Filter将返回原始数组中值的新数组,其中函数返回
true
。
var temp = current_films.filter(function(film) {
return (film.f_material === Value);
});
PS Could you please mention why the above code would not work?
你能否提一下为什么上面的代码不起作用? As in, if I put an alert("Reached here");, it's not getting executed.
就像在,如果我发出警报(“在这里到达”);它没有被执行。 Any ideas why its so?
任何想法为何如此?
I'd guess f_material is not defined for every element in the array. 我猜测f_material没有为数组中的每个元素定义。
If that's the case I'd use 如果是这种情况我会用
if(typeof(current_films[i].f_material)!=='undefined')
{
if(current_films[i].f_material == Value)
{
temp[i] = current_films[i];
}
}
Anyway I'd suggest you to get familiar with the browser's javascript debugger (assumed that code runs in a browser) 无论如何,我建议你熟悉浏览器的javascript调试器(假设代码在浏览器中运行)
Finally note that you're not copying the array/object: 最后请注意,您没有复制数组/对象:
temp[i] is a reference to current_films[i] temp [i]是对current_films [i]的引用
Modifying current_films later in the code will result in modifying temp 稍后在代码中修改current_films将导致修改temp
If that's not the behaviour desired Google for "javascript object copy". 如果这不是谷歌“javascript对象复制”所希望的行为。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.