Search code examples
javascriptjqueryarraysecmascript-6ecmascript-5

Merge array into object properties in JavaScript


I have a trivial issue where I have two simple objects like this

var state = {
    Value1: "Something",
    Value2: "Else"
};


var claims = [
    "Viewing",
    "Editing",
    "Delete"
];

and I would like to create an object that looks like this.

var newState = {
    Value1: "Something",
    Value2: "Else",

    /* Array merged into properties with defaults. */
    Viewing: true,
    Editing: true,
    Delete: true
};

I considered using jQuery $.map() and alternatively Object.assign() (which seems to be closer to what I want) but I cant seem to work out exactly how to achieve the result I need.

So as the heading states, how do I merge an array into an existing object as properties while also setting default values?


Solution

  • For the simple given example try the following:

    var state  = {Value1:"Something",Value2:"Else"}; 
        claims = ["Viewing","Editing","Delete"];
    
    let res = Object.assign(state, claims.reduce((a,c) => {a[c] = true; return a},{}))
    console.log(res)