Javascript Object push()函数 [英] Javascript Object push() function

查看:2835
本文介绍了Javascript Object push()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个javascript对象(我实际上通过ajax请求获取数据):

I have a javascript object (I actually get the data through an ajax request):

var data = {};

我添加了一些内容:

data[0] = { "ID": "1"; "Status": "Valid" }
data[1] = { "ID": "2"; "Status": "Invalid" }

现在我要删除状态无效的所有对象(但是保持一切顺序相同):

Now I want to remove all objects with an invalid status (but keep everything the ordering same):

var tempData = {};
for ( var index in data ) {
    if ( data[index].Status == "Valid" ) {
        tempData.push( data );
    }
}
data = tempData;

在我看来,所有这一切都应该有效,但我收到的错误是tempData.push是不是一个功能。我理解为什么它与数组不一样,但我能做什么呢?

In my mind, all of this should work, but I am getting an error that tempData.push is not a function. I understand why it isn't the same as an array, but what could I do otherwise?

推荐答案

push()适用于数组,而非对象,因此请使用正确的数据结构。

push() is for arrays, not objects, so use the right data structure.

var data = [];
// ...
data[0] = { "ID": "1", "Status": "Valid" };
data[1] = { "ID": "2", "Status": "Invalid" };
// ...
var tempData = [];
for ( var index=0; index<data.length; index++ ) {
    if ( data[index].Status == "Valid" ) {
        tempData.push( data );
    }
}
data = tempData;

这篇关于Javascript Object push()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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