Milos
Milos

Reputation: 619

How to dynamicaly create object keys and assign property to it

I have an array of objects and I want to check if some object has array as property, so if does, I want to create new dynamic keys with properties assigned to these keys. This is the array I have:

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_age: 45,
        customer_weapon: 'Magnum 357',
        customer_email: '[email protected]',
        customer_city: 'King County'
    },
]

and I want to reasign customer_email to new properties, so the output will be

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

also keeping the rest of the object properties. I've tried something like this

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()
    }
})

but it doesn't work well. What am I doing wrong? Thanks in advance!

Upvotes: 0

Views: 35

Answers (1)

Krunal Sonparate
Krunal Sonparate

Reputation: 1142

You are creating a new item object and returning that object so it is not keeping the older keys. I have modified your code logic.

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
})

Which will give you this output

[{
    "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_age": 45,
    "customer_weapon": "Magnum 357",
    "customer_email": "[email protected]",
    "customer_city": "King County"
}]

Considering you are expecting emailIDs with new keys only if email has array of emailIds and also keeping the other key values as well.

Upvotes: 1

Related Questions