Javascript在多维对象/数组中查找和删除值



我基本上需要的是在多维数组中找到项目并只删除它。问题是这里有多个相同的对象键。

数组示例(从控制台复制):

gameDetails.betsArray = [{
    '1.02': {
        userDetails: {
            socketID: '/#32EZlk6tW03tNgnOAAAA',
            userID: 1
        },
        trigger: 110,
        parseD: 1.02
    }
}, {
    '1.02': {
        userDetails: {
            socketID: '/#32EZlk6tW03tNgnOAAAA',
            userID: 5
        },
        trigger: 881,
        parseD: 1.02
    }
}]

数组如何生成

gameDetails.betsArray[validator.toFloat(betDetails.breakAt)] = {
    userDetails: {
        socketID: socketID,
        userID: connectedUsers[socketID].id
    },
    betAmount: validator.toInt(betDetails.amount),
    breakAt: validator.toFloat(betDetails.breakAt)
};

我想通过key(1.02)和object.userDetails.userID = 5 (

)找到对象

我已经尝试过了,但对我不起作用:

gameDetails.betsArray.map(function (details, key) {
    if (details.userDetails.userID == connectedUsers[socketID].id &&
        details.trigger == validator.toFloat(betDetails.trigger)) {
        delete gameDetails.betsArray[key];
    }
});

怎么可能?在最后一步中,我想从找到的对象数组中删除数据。

尝试用有效的数据结构和Array#filter求解

[
    {
        "1.02": {
            "userDetails": {
                "socketID": "/#32EZlk6tW03tNgnOAAAA",
                "userID": 1
            },
            "trigger": 110,
            "parseD": 1.02
        }
    },
    {
        "1.02": {
            "userDetails": {
                "socketID": "/#32EZlk6tW03tNgnOAAAA",
                "userID": 5
            },
            "trigger": 881,
            "parseD": 1.02
        }
    }
]

var data = [{ '1.02': { userDetails: { socketID: '/#32EZlk6tW03tNgnOAAAA', userID: 1 }, trigger: 110, parseD: 1.02 } }, { '1.02': { userDetails: { socketID: '/#32EZlk6tW03tNgnOAAAA', userID: 5 }, trigger: 881, parseD: 1.02 } }];
data = data.filter(function (a) {
    return !a['1.02'] || a['1.02'].userDetails.userID !== 5;
});
console.log(data);

首先你需要将你的数据结构更改为有效的javascript数据,例如像这样的对象数组,然后你可以使用filter()

var obj = [{
  '1.02': {
    userDetails: {
      socketID: '/#32EZlk6tW03tNgnOAAAA',
      userID: 1
    },
    trigger: 110,
    parseD: 1.02
  }
}, {
  '1.02': {
    userDetails: {
      socketID: '/#32EZlk6tW03tNgnOAAAA',
      userID: 5
    },
    trigger: 881,
    parseD: 1.02
  }
}]
var result = obj.filter(function(e) {
  if (e['1.02'] && e['1.02'].userDetails.userID == 5) return e;
});
console.log(result)

相关内容

  • 没有找到相关文章

最新更新