将字符串数组映射为对象属性

时间:2018-12-10 20:58:35

标签: javascript arrays reactjs

我有一个像这样的数组。

const array =["king", "henry", "died", "while", "drinking", "chocolate", "milk"]

我有以下初始状态

state = {
options:{}
}

如果我想将此数组映射到我的状态,并将每个索引字符串分配为this.state.options的属性,我该怎么做?

所以最终结果将是:

console.log(this.state.options)
  

输出:{国王:空,亨利:空,死:空,而:空,喝酒:空,巧克力:空,牛奶:空}

我认为此后它将是不确定的,而不是null ...但是有什么建议吗?

8 个答案:

答案 0 :(得分:5)

我相信您是在寻找reduce而不是map

const array =["king", "henry", "died", "while", "drinking", "chocolate", "milk"];

const state = {
  options: array.reduce( (current, item) => {
      current[item] = null;
      return current;
    }, {})
};

console.log( state );

答案 1 :(得分:3)

您可以使用适当的Object.fromEntries函数:

const array = ["king", "henry", "died", "while", "drinking", "chocolate", "milk"];
state = {
    options: Object.fromEntries(array.map(value => [ value, null ]))
};

您的用户代理可能不向Object.fromEntries提供脚本宿主,但是您可以使用替代方法,直到它提供为止:

if(!Object.fromEntries)
    Object.fromEntries = entries => entries.reduce((result, entry) => (result[entry[0]] = entry[1], result), {});

我更喜欢使用我希望在以后广泛使用的语言或API部分,方法是提供一个备用实现,直到这些时间可用为止,届时代码将在不做任何修改的情况下使用本机实现自动(上面的代码显然是有条件的替代或polyfill,也称为条件填充)。

答案 2 :(得分:0)

您可以执行以下操作:

const array =["king", "henry", "died", "while", "drinking", "chocolate", "milk"];
const state = {options: {}};
array.forEach((e, i) => state.options[e] = i);

答案 3 :(得分:0)

您可以逐步执行此操作:

const array =["king", "henry", "died", "while", "drinking", "chocolate", "milk"];

// We make a new options object which will be filled with the array's key / values
const options = {};

// Iterate through the array and fill the object
for ( let i = 0 ; i < array.length ; i++ ) {
    options[array[i]] = null
}

// At this point options === { "kind": null, "henry": null ... }

this.setState( { options } );

您可以进一步简化它:

// Check reduce at MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
const options = array.reduce( ( result, key ) => {
   result[key] = null;
   return result;
}, {} );

this.setState( { options } );

甚至更好

this.setState( {
    options: array.reduce( ( result, key ) => Object.assign( result, {
        [key]: null
    } ), {} );
} );

答案 4 :(得分:0)

使用Array.reduce,您可以执行以下操作:

const data = ["king", "henry", "died", "while", "drinking", "chocolate", "milk"]

const state = { options: data.reduce((a,c) => (a[c] = null, a), {}) }

console.log(state)

这种方法和Array.forEach一种方法最有意义,因为您只执行了一个循环就可以装饰对象。否则,您必须执行两次或更多次,这显然不是很有效(对于Object.assign / Object.fromEntries + Array.map

答案 5 :(得分:0)

您可以映射单个对象并将所有对象分配给单个对象。

const
    array = ["king", "henry", "died", "while", "drinking", "chocolate", "milk"],
    state = { options: Object.assign(...array.map(k => ({ [k]: null }))) };

console.log(state);

答案 6 :(得分:0)

以上大多数选项看起来都是一种不错的方法。今天,我需要一些类似的功能(将2d数组转换为obj.key:val),并尝试使用Object.fromEntities,但是我意识到这只是Firefox,正如Akrion所述。

这是我使用的解决方案。

var array = ["king", "henry", "died", "while", "drinking", "chocolate", "milk"];

function objFromArray(arr){
    var obj = {};
    arr.forEach(row=>{
        Object.defineProperty(obj, row,{
        value: null,
        writable: true
        });
    });
    return obj;
}
objFromArray(array);

答案 7 :(得分:0)

您可以这样做:

state = {
    options: {}
}

array =["king", "henry", "died", "while", "drinking", "chocolate", "milk"]

render(){
    return(
        <div>
            {this.array.forEach(value => this.state.options[value] = (this.array[value]=null))}
            {Object.keys(this.state.options).forEach(value => console.log(value,this.state.options[value]))}
        </div>
    ) 
}