javascript 如何从此数据结构中删除javascript对象中的数据?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8979234/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 05:12:29  来源:igfitidea点击:

How to delete data from the javascript object from this data structure?

javascriptarrays

提问by Jenan

I need to read all the connection times. (connectionTimes) I need to delete the line - when it will be offline more than online:

我需要阅读所有的连接时间。(connectionTimes) 我需要删除该行 - 当它离线多于在线时:

    userId: 1,
    connectionTimes:
        [
            {onlineTime:"11:10:30", offlineTime:"11:18:12"}, //delete
            {onlineTime:"11:14:14", offlineTime:"11:52:41"}  //delete
        ]

Delete user id - When times the connection will be empty.

删除用户 ID - 连接何时为空。

 userId: 1, //delete userid
        connectionTimes:
            [
                //empty connection
            ]

I have this data structure:

我有这个数据结构:

var users = [];

    users[0] = {
        userId: 1,
        connectionTimes:
            [
                {onlineTime:"11:10:30", offlineTime:"11:18:12"},
                {onlineTime:"11:14:14", offlineTime:"11:52:41"}
            ]
    }

    users[1] = {
        userId: 2,
        connectionTimes: 
            [
                {onlineTime:"8:08:14", offlineTime:"1:15:00"}
            ]
    } 

回答by Andreas Koch

You can delete a property from an JavaScript object with the delete operator:

您可以使用 delete 运算符从 JavaScript 对象中删除属性:

var sampleObject = {
    "key1": "value1",
    "key2": "value"
};
delete sampleObject["key2"];

or like this:

或者像这样:

delete sampleObject.key2

See the Mozilla Developer Network JavaScript Reference for more background on the delete operator: https://developer.mozilla.org/en/JavaScript/Reference/Operators/delete

有关删除运算符的更多背景信息,请参阅 Mozilla 开发者网络 JavaScript 参考:https: //developer.mozilla.org/en/JavaScript/Reference/Operators/delete

Your specific example would look something like this:

您的具体示例如下所示:

for(var id in users) {
    var user = users[id];
    if (user.connectionTimes.length === 0) {
        delete users[id];
        break
    }

    for(var i=0; i<=user.connectionTimes.length; i++) {
        var connectionTime = user.connectionTimes[i];
        if (connectionTime.onlineTime < connectionTime.offlineTime) {
            delete users[id];
            break;
        }
    }
}

Here is a link to jsFiddle showing the code in action: http://jsfiddle.net/Q86Jd/

这是 jsFiddle 的链接,显示了正在运行的代码:http: //jsfiddle.net/Q86Jd/

回答by hugomg

There are many ways to remove things from arrays in Javascript. The mains ones I can think of are

有很多方法可以从 Javascript 中的数组中删除内容。我能想到的主线是

  • The deleteoperator. Using it sets the chosen position to undefined and is similar to just setting the element to null. (The main difference is that deleting a key will cause it to be skiped when iterating with the forEach and map array methods).

    var xs = [0,1,2];
    delete xs[1];
    console.log(xs); // [0, undefined, 2]
    
  • The splicemethod can remove a chunk or the array, moving the remaining elements left to fill it in.

    var xs = [0,1,2,3];
    xs.splice(2, 1); //index, ammount to remove
    console.log(xs); // [0,1,3]
    
  • Setting the array's lengthproperty truncates it. This can be used to manually remove elements the old fashioned way when you want more control.

    var xs = [0,1,2,3];
    xs.length = 2;
    console.log(xs); // [0,1]
    xs.length = 4;
    console.log(xs); // [0,1, undefined, undefined]
    
  • delete运营商。使用它将所选位置设置为未定义,类似于将元素设置为空。(主要区别在于,在使用 forEach 和 map 数组方法进行迭代时,删除一个键会导致它被跳过)。

    var xs = [0,1,2];
    delete xs[1];
    console.log(xs); // [0, undefined, 2]
    
  • splice方法可以删除一个块或数组,将剩余的元素向左移动以填充它。

    var xs = [0,1,2,3];
    xs.splice(2, 1); //index, ammount to remove
    console.log(xs); // [0,1,3]
    
  • 设置数组的length属性会截断它。当您需要更多控制时,这可用于以老式方式手动删除元素。

    var xs = [0,1,2,3];
    xs.length = 2;
    console.log(xs); // [0,1]
    xs.length = 4;
    console.log(xs); // [0,1, undefined, undefined]
    


So in your case we might do something like this:

所以在你的情况下,我们可能会做这样的事情:

function filter_in_place(array, predicate){
    var j=0;
    for(var i=0; i<arr.length; i++){
        var x = arr[i];
        if(pred(x)){
            arr[j++] = x;
        }
    }
    arr.length = j;
}

for(var i=0; i < users.length; i++){
    filter_in_place( users[i].connections, function(conn){
        /*return if offline larger then online*/
    });
}

filter_in_place(users, function(user){ return user.connections.length > 0; });

回答by Niet the Dark Absol

Basically you want to use something like this:

基本上你想使用这样的东西:

for( var i=0; i<users.length; i++) {
    for( var j=0; j<users[i].connectionTimes.length; j++) {
        if( users[i].connectionTimes[j].onlineTime < users[i].connectionTimes[j].offlineTime) {
            delete users[i].connectionTimes[j];
            j--;
        }
    }
    if( users[i].connectionTimes.length == 0) {
        delete users[i];
        i--;
    }
}

回答by Jordan Running

This is pretty straightforward. In pseudocode:

这很简单。在伪代码中:

declare user, times

for each index in users
  set user  = users[ index ]
  set times = user.connectionTimes

  if times is empty
    then delete users[ index ]

  else
    declare onlineSecs, offlineSecs

    for each index2 in times
      set onlineSecs  = timeInSeconds( times[ index2 ].onlineTime )
      set offlineSecs = timeInSeconds( times[ index2 ].offlineTime )

      if offlineSecs > onlineSecs
        then delete times[ index2 ]

In JavaScript the command to delete a variable is deleteand can be used on arrays the same, e.g. delete someArray[ someIdx ];. The implementation of timeInSecondswill be something like this:

在 JavaScript 中,删除变量的命令是delete并且可以在相同的数组上使用,例如delete someArray[ someIdx ];. 的实现timeInSeconds将是这样的:

function timeInSeconds( timeWithColons ) {
  var hrsMinsSecs = "12:34:56".split(':');

  return ( parseInt( hrsMinsSecs[0] ) * 60 +
           parseInt( hrsMinsSecs[1] )
         ) * 60 +
         parseInt( hrsMinsSecs[2] )
  ;
}