Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

javascript - Javascript Object push()函数(Javascript Object push() function)

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

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

var data = {};

I have added some stuff into it:

(我添加了一些东西:)

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;

In my mind, all of this should work, but I am getting an error that tempData.push is not a function.

(在我看来,所有这一切都应该工作,但我收到一个错误, tempData.push不是一个函数。)

I understand why it isn't the same as an array, but what could I do otherwise?

(我理解为什么它与数组不一样,但我能做什么呢?)

  ask by Andrew Jackman translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...