如何将对象所有键替换为指定数组元素?实现类似PHP array_combine功能
实现类似PHP array_combine的JavaScript函数
需求:实现一个函数,接收目标键数组与对象,将对象的所有键替换为数组中对应的元素,功能对标PHP的array_combine函数。
示例代码与实现
const data = { 0: { text: 'hello' }, 1: { text: 'hi' }, 2: { text: 'hay!' } }; function arrayCombine(keys, values) { const valueList = Object.values(values); return keys.reduce((result, key, index) => { if (index < valueList.length) { result[key] = valueList[index]; } return result; }, {}); } console.log(arrayCombine([10, 20, 37], data));
输出结果
{ 10: { text: 'hello' }, 20: { text: 'hi' }, 37: { text: 'hay!' } }
实现说明
- 用
Object.values()提取原对象的所有值,保证值的顺序与原对象键的遍历顺序一致(ES6+规范下,对象会按数字键升序、字符串键插入顺序遍历)。 - 通过
reduce遍历新键数组,将每个键与原对象对应位置的值绑定,构建新对象。 - 加入索引越界判断:若新键数组长度大于原对象值的数量,多余的键会被忽略;若原对象值的数量多于新键数组,多余的值也不会被纳入新对象。
内容的提问来源于stack exchange,提问作者Amirali Pourmoshir
相关产品推荐
相关产品推荐

