【问题标题】:Get last element of a JSON array in TypeScript在 TypeScript 中获取 JSON 数组的最后一个元素
【发布时间】:2020-06-15 02:03:58
【问题描述】:

我需要获取 JSON 对象数组中最后一个元素的“id”属性的值。我可以通过 id 找到每个元素,但我还需要获取 JSON 对象数组中最后一个“id”的值。在下面的示例中,它是“3”。提前致谢!

let types: any[] =
    [
        {'id': '0', 'value': ''},
        { 'id': '1', 'value': '' },
        { 'id': '2', 'value': '' },
        { 'id': '3', 'value': '' },
    ]; 

let index = 0;
let indexNext = 1;
types.forEach((item) => { 
    if (item.id == index) { 
        item.value = 'Book';
        console.log(item.value); //Book
    }
    if (item.id == indexNext) { 
        item.value = 'Magazine';
        console.log(item.value); //Magazine
    }
})

【问题讨论】:

    标签: json typescript angular6


    【解决方案1】:

    试试这个:

    types[types.length - 1]['id']

    【讨论】:

    • 那更短。谢谢@JGFMK!
    【解决方案2】:

    types[types.length - 1] 为您提供types 的最后一个元素。

    如果您调用 forEach 对数组中的每一项执行某项操作,然后执行与最后一项不同的操作,则 Array#forEach 的回调参数将传递一个索引(作为该项之后的参数)。所以你可以写types.forEach((item, indexForItem) => { ... });,然后比较indexForItemtypes.length - 1,看看你是否在最后一个。

    【讨论】:

    • index 参数和 types[types.length -1] 一样,非常感谢!这是代码:types.forEach((item, indexForItem) => { var t = types[types.length - 1]; if (t.id == indexForItem) { console.log('The last id is: ' + t.id); // The last id is: 3 } });
    猜你喜欢
    • 2016-09-29
    • 2017-08-27
    • 2017-11-08
    • 2022-09-29
    • 2012-08-18
    • 1970-01-01
    • 2011-09-09
    • 2016-08-26
    • 1970-01-01
    相关资源
    最近更新 更多