【问题标题】:Remove specific element from json array从 json 数组中删除特定元素
【发布时间】:2019-08-14 17:36:55
【问题描述】:

我声明一个这样的 JSON

var json{
section1: [],
section2: [],
section3: []
} 

我想删除这种方式的特定项目或类似的东西

json[section][index].remove();

我试过这种方式

 delete json[section][index];

但是当我这样做时,数组元素不会重新排列

【问题讨论】:

  • 您可以使用splice() 从数组中删除一个项目。 --> stackoverflow.com/questions/5767325/…
  • 如果你只是想删除一个基于名为index的特定属性,你可以这样做delete json["section"+index]

标签: javascript jquery arrays json


【解决方案1】:

数组没有remove 函数。请改用splice

var data = {section1: [1,2,3,4]};

const remove = (arr, key, index) => arr[key].splice(index,1)

remove(data,"section1",2)

console.log(data)

请记住,这实际上会更改原始数组。

【讨论】:

    【解决方案2】:

    slice() 是你的朋友。

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

    json[section] = json[section].slice(index,index+1);
    

    【讨论】:

    • Slice 将返回一个浅拷贝(在本例中为数组的单个元素)。您不会更改原始数组,也不会返回任何类型的更改数组。你把切片和拼接混在一起了吗?
    • 诚然,问题中并不清楚他们正在操作的数组是否不仅仅是一个简单的数组。 @assoron,无论如何你的答案更好。为了完整起见,我将把这个留在这里。
    • 我使用切片来移除元素。我做了这样的事情: json[place].splice(position, 1);谢谢!
    猜你喜欢
    • 2019-06-03
    • 2021-04-21
    • 2016-08-02
    • 2020-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多