javascript 将字符串数组Map为对象属性

rbl8hiat  于 2023-02-07  发布在  Java
关注(0)|答案(8)|浏览(122)

我有一个这样的数组。

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

我有下面的初始状态

state = {
options:{}
}

如果我想把这个数组Map到我的状态,并把每个索引字符串作为this.state.options的一个属性赋值,我该怎么做呢?
所以最终结果会是:

console.log(this.state.options)

输出:{国王:空,亨利:空,死亡:空,而:空,饮酒:空,巧克力:空,牛奶:空}
我认为在那之后它将是未定义的而不是空的...但是有什么建议吗?

ufj5ltwl

ufj5ltwl1#

我相信您更愿意寻找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 );
b09cbbtk

b09cbbtk2#

可以使用Object.fromEntries函数:

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

您的用户代理可能不会为Object.fromEntries提供其脚本主机--该函数是ECMAScript 2019(又称第10版)的一部分--但您可以使用一个替代项,直到它提供:

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

我更喜欢使用我希望以后广泛使用的语言或API的一部分,通过提供一个替代实现,直到这些实现可用为止,届时代码将自动使用本地实现,无需任何修改(以上显然是一个条件替代或 polyfill,因为它也被称为)。

zpqajqem

zpqajqem3#

您可以逐步执行此操作:

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
    } ), {} );
} );
3hvapo4f

3hvapo4f4#

您可以执行以下操作:

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

bwntbbo35#

可以Map单个对象,并将所有对象指定给单个对象。

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

console.log(state);
i7uaboj4

i7uaboj46#

使用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的情况下)

5vf7fwbs

5vf7fwbs7#

上面的大多数选项看起来都是一个不错的方法。今天我需要一些类似的功能(将2D数组转换为obj.key:瓦尔),并试图使用Object.fromEntities,但意识到它只像Akrion所说的那样是Firefox。
这是我用的溶液。

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);
vnzz0bqm

vnzz0bqm8#

你可以这样做:

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

相关问题