将数组合并到JavaScript中的对象属性中

时间:2019-07-03 11:30:30

标签: javascript jquery arrays ecmascript-6 ecmascript-5

我有一个小问题,我有两个像这样的简单对象

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


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

我想创建一个看起来像这样的对象。

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

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

我考虑过使用jQuery $.map()Object.assign()(似乎更接近我想要的),但是我似乎无法确切地找到如何实现所需的结果。

因此,作为标题状态,如何将数组作为属性合并到现有对象中,同时还要设置默认值?

4 个答案:

答案 0 :(得分:2)

对于简单的示例,请尝试以下操作:

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)

答案 1 :(得分:0)

您可以使用带有obj[myStringAsName] = value的变量名来添加属性

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


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

var newState = state;
claims.forEach(function(item){
	newState[item] = true;
})

console.log(newState)

答案 2 :(得分:0)

我使用reduce将数组转换为对象并合并了两个对象

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


var claims = [
    "Viewing",
    "Editing",
    "Delete"
];
var obj = claims.reduce(function(acc, cur) {
            acc[cur] = true;
            return acc;
          }, {});

var returnedData = Object.assign(state, obj);

console.log(returnedData)

答案 3 :(得分:0)

您可以使用解构和简单的Array#forEach

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


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

const newState = {
  ...state
}

claims.forEach(prop => newState[prop] = true);

console.log(newState)