JS - 从数组中删除对象

时间:2018-04-03 15:39:19

标签: javascript

我想从我的表/数组中删除一个对象(索引)

var item = [
{name:'test1',variable:20},
{name:'test2',variable:20},
{name:'test3',variable:20},
{name:'test4',variable:20},
{name:'test5',variable:20},
{name:'test6',variable:20},
{name:'test7',variable:20},
{name:'test8',variable:20}]

例如我想删除对象编号2(item.name = test3),我该怎么做?

6 个答案:

答案 0 :(得分:2)

您只需致电:

delete item[2]

答案 1 :(得分:2)

另一种选择......

item = item.filter(e=>e.name!=="test3")

答案 2 :(得分:0)

您可以使用splice()findIndex()方法。



var item = [{name:'test1',variable:20},{name:'test2',variable:20},{name:'test3',variable:20},{name:'test4',variable:20},{name:'test5',variable:20},{name:'test6',variable:20},{name:'test7',variable:20},{name:'test8',variable:20}]

item.splice(item.findIndex(({name}) => name == 'test3'), 1);
console.log(item)




答案 3 :(得分:0)

您也可以使用拼接,但要小心,因为它会修改实际的数组

var item = [
{name:'test1',variable:20},
{name:'test2',variable:20},
{name:'test3',variable:20},
{name:'test4',variable:20},
{name:'test5',variable:20},
{name:'test6',variable:20},
{name:'test7',variable:20},
{name:'test8',variable:20}]

item.splice(2,1)

console.log(item)

答案 4 :(得分:0)

function remove(array, element) {
    return array.filter(e => e !== element);
}

const vowelsAndX = ["a", "e", "i", "o", "u", "x"];
const vowels = remove(vowelsAndX, "x");
vowels.toString(); // "a,e,i,o,u"

----------------------------------------------------------------------------


var item = [
    {name:'test1',variable:20},
    {name:'test2',variable:20},
    {name:'test3',variable:20},
    {name:'test4',variable:20},
    {name:'test5',variable:20},
    {name:'test6',variable:20},
    {name:'test7',variable:20},
    {name:'test8',variable:20}];

    function remove(array, element) {
        return array.filter(e => e !== element);
    }

    const restOfItems = remove(item, item[0]);
    console.log(restOfItems)

答案 5 :(得分:0)

import csv
import pprint
portfolio = {}

def loadPortfolio(fname):
    try:
        with open(fname, "rt") as f:
            reader = csv.reader(f)
            for row in reader:
                key = row[0]
                portfolio[key] = row[1:]
        pprint.pprint(portfolio)