Home > Back-end >  How to assign values from an object to properties in an array, conditionally
How to assign values from an object to properties in an array, conditionally

Time:07-12

I need to assign values from an array of objects, to an object, with different keys.

In the JavaScript app, I'm working with, I get an array of objects returned similar to below:

urlArrayOfObjects = [ 

    {url: 'https://amazon.co.uk', country: 'uk'},
    {url: 'https://amazon.com', country: 'usa'},
    {url: 'https://amazon.ca', country: 'canada'},
    {url: 'https://amazon.es', country: 'spain'}
]

The object is the something like the following:

urlTables = {
    short_url_id: "",
    uk_url: "",
    usa_url: "",
    canada_url: "",
    irland_url: "",
    spain_url: "",
    germany_url: "",
    default_country: "",
    default_url: "",
    customer_id: ""
}

I need to extract values from urlArrayOfObjects and insert them into the appropriate properties in the urlTables (And if there are no values, if should default to null

For e.g. in the above case, urlTables should look like the following after I'm done with it:

urlTables = {
    short_url_id: null,
    uk_url: "https://amazon.co.uk",
    usa_url: "https://amazon.com",
    canada_url: "https://amazon.ca",
    irland_url: null,
    spain_url: "https://amazon.es",
    germany_url: null,
    default_country: null,
    default_url: null,
    customer_id: null}

What is the best way of going about achieving this? Thank you so much for your help!

CodePudding user response:

This is an area where JavaScript, as compared to a strongly typed language really shines. You can simply fetch the values and use them as field names.

For example:

urlTables[urlArrayOfObjects[0].country "_url"] = urlArrayOfObjects[0].url;

The idea is the same for everything else so you just need to loop.

Here's an example loop:

for(var item of urlArrayOfObjects){
    urlTables[item.country   "_url"] = item.url;
}

CodePudding user response:

I would do it like this:

let urlArrayOfObjects = [ 

    {url: 'https://amazon.co.uk', country: 'uk'},
    {url: 'https://amazon.com', country: 'usa'},
    {url: 'https://amazon.ca', country: 'canada'},
    {url: 'https://amazon.es', country: 'spain'}
]

let urlTables = {
    short_url_id: null,
    uk_url: null,
    usa_url: null,
    canada_url: null,
    irland_url: null,
    spain_url: null,
    germany_url: null,
    default_country: null,
    default_url: null,
    customer_id: null
}


console.log(
    urlArrayOfObjects.reduce((carry, current) => {
        return {
            ...carry,
            [current.country   '_url']: current.url
        }
    }, urlTables)
);

  • Related