在对象中特定键值的末尾附加另一个值

我有一个对象数组,如下所示:


const sample = [

{

    key:"key1",

    title: "title1", 

    value: "value1"

},

{

    key:"key2",

    title: "title2", 

    value: "value2"

},

{

    key:"key3",

    title: "title3", 

    value: "value3"

}

]


现在我想在每个对象“标题”键的末尾附加一些值,如下所示:


const sample = [

{

    key:"key1",

    title: "title1 + 1", 

    value: "value1"

},

{

    key:"key2",

    title: "title2 + 2", 

    value: "value2"

},

{

    key:"key3",

    title: "title3 + 3", 

    value: "value3"

}

]


我知道如何修改、添加密钥,但不确定如何以这种方式附加数据。请针对上述问题提出一些解决方案。



慕村9548890
浏览 126回答 3
3回答

慕森王

您可以通过获取值的索引来映射对象。const    sample = [{ key:"key1", title: "title1",  value: "value1" }, { key:"key2", title: "title2",  value: "value2" }, { key:"key3", title: "title3",  value: "value3" }],    result = sample.map((o, i) => ({ ...o, title: o.title + (i + 1) }));console.log(result);.as-console-wrapper { max-height: 100% !important; top: 0; }

繁星coding

希望这会有所帮助:) 根据需要在地图中转换值!:)const sample = [    {        key:"key1",        title: "title1 + 1",        value: "value1"    },    {        key:"key2",        title: "title2 + 2",        value: "value2"    },    {        key:"key3",        title: "title3 + 3",        value: "value3"    }];const other = sample.map(val => ({...val, title: val.title + 'anything'}));console.log(other);

慕桂英4014372

const sample = [{    key:"key1",    title: "title1",     value: "value1"},{    key:"key2",    title: "title2",     value: "value2"},{    key:"key3",    title: "title3",     value: "value3"}]let result = sample.map((x, i) => {  x.title = x.title + ' + ' + (i + 1);  return x;});console.log(result);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript