如何动态创建对象键并为其分配属性

问题描述

我有一个对象数组,我想检查某个对象是否具有数组作为属性,因此,如果要这样做,我想创建具有分配给这些键的属性的新动态键。这是我拥有的数组:

const arr = [
    {
        customer_name: 'Negan',customer_age: 45,customer_weapon: 'Bat',customer_email: '[email protected]',customer_city: 'Washington'
    },{
        customer_name: 'Daryl',customer_age: 41,customer_weapon: 'Crossbow',customer_email: ['[email protected]','[email protected]','[email protected]'],customer_city: 'Atlanta'
    },{
        customer_name: 'Rick',customer_weapon: 'Magnum 357',customer_email: '[email protected]',customer_city: 'King County'
    },]

并且我想将customer_email重新分配给新属性,所以输出将是

[{email1: '[email protected]',email2: '[email protected]',email3: '[email protected]'}]

还保留其余的对象属性。我已经尝试过这样的事情

const arr1 = arr.map((item,index) => {
    const emails = item.customer_email.toString().split(",");

    let list = [];
    for (var i = 0; i < arr.length; i++) {
        var item = {};
        item['emails' + i] = emails[i];
        list.push(item);
    }

    console.log('list',list);

    return {
        email1: emails.shift(),email2: emails.shift(),email3: emails.shift()
    }
})

但是效果不佳。我究竟做错了什么?预先感谢!

解决方法

您正在创建一个新的项目对象并返回该对象,因此它不会保留旧的键。我已经修改了您的代码逻辑。

const arr1 = arr.map((item,index) => {

    if( Array.isArray(item.customer_email))
    {
        for (var i = 0; i < item.customer_email.length; i++) {
            item['emails' + i] = item.customer_email[i];
        }
    }
    return item
})

哪个会给你这个输出

[{
    "customer_name": "Negan","customer_age": 45,"customer_weapon": "Bat","customer_email": "[email protected]","customer_city": "Washington"
},{
    "customer_name": "Daryl","customer_age": 41,"customer_weapon": "Crossbow","customer_email": ["[email protected]","[email protected]","[email protected]"],"customer_city": "Atlanta","emails0": "[email protected]","emails1": "[email protected]","emails2": "[email protected]"
},{

    "customer_name": "Rick","customer_weapon": "Magnum 357","customer_email": "[email protected]","customer_city": "King County"
}]

考虑到您仅在电子邮件具有emailId数组且还保留其他键值的情况下,才期望使用新密钥的emailID。