使用名称/值从 json 数组添加项

Add item from json array using its name / value

本文关键字:json 数组 添加 值从      更新时间:2023-09-26

我知道如何从 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
 }

我只是假设长度和推送黑客有效,因为我自己从未使用过它们。