js 怎样把一个keys数组和values数组合并成一个object

muyun
  • 175

js 怎样把一个keys数组和values数组合并成一个object

回复
阅读 4.1k
7 个回答
for(var i = 0; i < arrKey.length; i++){

   obj[arrKey[i]] = arrValue[i];

}

用json来存,如var obj={},obj[i].key='key',obj[i].value='value'

function makeObject(keys, values) {
    let obj = {};
    
    keys.forEach((key, index) => {
        obj[key] = values[index];
    });
    
    return obj;
}
var keys=['k1','k2','k3'],values=['v1','v2','v3'];
var obj={};
for(var i=0;i<keys.length;i++){
   obj[keys[i]]=values[i]
}
console.log(obj);
const ArraytoObj = (keys = [], values = []) => {
  if(keys.length === 0 || values.length === 0) return {}
  const len = keys.length > values.length ? values.length : keys.length
  // if you want save all the keys, and the value could be undefined, you can use keys.forEach function instead of for loop
  const obj = {}
  for(let i = 0; i < len; ++i) {
    obj[keys[i]] = values[i]
  }
    return obj
}

// test cases
expect(ArraytoObj(['ka', 'kb'], ['va', 'vb'])).to.eql({ ka: 'va', kb: 'vb' })
expect(ArraytoObj(['ka', 'kb', 'kc'], ['va', 'vb'])).to.eql({ ka: 'va', kb: 'vb' })
expect(ArraytoObj(['ka', 'kb'], ['va', 'vb', 'vc'])).to.eql({ ka: 'va', kb: 'vb' })
expect(ArraytoObj([], ['va', 'vb'])).to.eql({})
expect(ArraytoObj(['ka', 'kb'], [])).to.eql({})
expect(ArraytoObj()).to.eql({})
let baseKey = ['id', 'title', 'goods_id']
let baseVal = ['秒杀活动id', '活动名', '商品id']

// 简单封装
let compose = (baseKey, baseVal) => {
    let optObj = {};
    baseKey.forEach((param, __index) => {
        optObj[param] = baseVal[__index]
    });
    return optObj;
};
    
 let o = compose(baseKey, baseVal)

  // {id: "秒杀活动id", title: "活动名", goods_id: "商品id"}
    
const keys = ["a", "b", "c", "d"];

const values = [1, 2, 3, 4, 5, 6, 7, 8];

const mergeKeyValue = (keys, values) => 
    keys
      .slice(0, Math.min(keys.length, values.length)) // 这一步为了取出两个数组最短长度,如果不做这一步,那就需要考虑某一方不存在值的情况
      .reduce((target, key, index) => ({ ...target, [key]: values[index]}), {});

mergeKeyValue(keys, values)
// 输出:{a: 1, b: 2, c: 3, d: 4}
宣传栏