如何从node.js中的json对象数组中删除特定的json对象

时间:2015-05-08 06:06:40

标签: node.js underscore.js

我有一个json对象数组,例如

 var user =[ { id: 1, name: 'linto', img: 'img' },
  { id: 2, name: 'shinto', img: 'img' },
  { id: 3, name: 'hany', img: 'img' } ]

由此,我需要删除一个特定的json对象

{ id: 2, name: 'shinto', img: 'img' }.

即输出数组应该是这样的

[ { id: 1, name: 'linto', img: 'img' },
  { id: 3, name: 'hany', img: 'img' } ]

node.js中是否有任何功能可以实现这一目标?

2 个答案:

答案 0 :(得分:0)

使用delete命令。

E.g。

delete user[index]

编辑:splice命令在数组的情况下效果更好,因为它完全删除了元素。如果删除null,则替换已删除的元素。

user.splice(0,<index>);

完整代码:

var user =[ { id: 1, name: 'linto', img: 'img' },
  { id: 2, name: 'shinto', img: 'img' },
  { id: 3, name: 'hany', img: 'img' } ]

  alert(JSON.stringify(user));

  user.splice(0,1);

  alert(JSON.stringify(user));

答案 1 :(得分:0)

There is an underscore way for the same.

reject

socket.on('join' function() {
// send message
});

socket.on('leave' function() {
// send message
});
.navigation {
    /* width: 400px; */
    margin: 0;
    padding: 0;
}

.navigation li ul {
    position: absolute;
    display: none;
    width: inherit;
    left: -20px;
}

.navigation li {
    display: inline;
    position: relative;
}