使用名称/值从 json 数组添加项
Add item from json array using its name / value
我知道如何从 json 数组中删除项目,但在添加时我似乎无法使其工作。
数组:
var users = [
{name: 'james', id: '1'}
]
想要添加,所以它变成:
var users = [
{name: 'james', id: '1'},
{name: 'thomas', id: '2'}
]
下面是删除数组的代码:
Array.prototype.removeValue = function(name, value){
var array = $.map(this, function(v,i){
return v[name] === value ? null : v;
});
this.length = 0; //clear original array
this.push.apply(this, array); //push all elements except the one we want to delete
}
removeValue('name', value);
//space removed
我需要进行哪些更改才能反转才能向数组添加值?
with Array.prototype.push()
?
var sports = ["plongée", "baseball"];
var total = sports.push("football", "tennis");
console.log(sports); // ["plongée", "baseball", "football", "tennis"]
console.log(total); // 4
我认为比map
更合适的函数filter
。
Array.prototype.removeValue = function(name, value){
var array = $.filter(this, function(v,i){
return v[name] !== value;
});
this.length = 0; //clear original array
this.push.apply(this, array); //push all elements except the one we want to delete
}
我只是假设长度和推送黑客有效,因为我自己从未使用过它们。
相关文章:
- 需要帮助设置json数组
- 如何使用 node.js 比较两个 json 数组
- 根据id将json数组组合为一个json数组
- 如何创建JSON数组
- 如何将package.json数组传递给grunt.js
- 访问json数组中的对象
- JSON数组数据返回Undefined
- 如何向JSON数组动态添加属性
- 如何从json数组中获取特定值
- 从多维嵌套json数组创建下拉列表
- 在ListView中添加JSON数组中存储的图像-ReactNative
- jquery在json数组中循环
- 将 JSON 数组解析为 JavaScript 数组
- 如何在php中读取没有任何键的JSON数组
- 如何在Jquery中迭代JSON数组
- 如何在cycle js中从JSON数组创建组件
- 如何使用jquery返回php-json数组对象
- JSON数组转换为JS对象数组
- 使用System从C#集合创建JSON数组.网状物剧本序列化
- 使用Underscore.js修改json数组中所选元素的更有效方法