最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to set the same value on multiple keys - Stack Overflow

programmeradmin4浏览0评论

How is it possible to set the same value on multiple keys? For example I have the following object:

const obj = {
   a: 5,
   b: 5,
   c: 5,
   d: 6
}

Is there any easy way for example lets say I have array of [a, b, c] (keys) and to spread them in object and set them as keys with same value. Point is to look more classy for example:

const keys =[a, b, c]
const obj = {
  [...keys]: 5
}

I know this would throw error but looking for some shorthand to achieve this

How is it possible to set the same value on multiple keys? For example I have the following object:

const obj = {
   a: 5,
   b: 5,
   c: 5,
   d: 6
}

Is there any easy way for example lets say I have array of [a, b, c] (keys) and to spread them in object and set them as keys with same value. Point is to look more classy for example:

const keys =[a, b, c]
const obj = {
  [...keys]: 5
}

I know this would throw error but looking for some shorthand to achieve this

Share Improve this question edited May 26, 2020 at 20:15 custommander 18.9k5 gold badges67 silver badges93 bronze badges asked May 26, 2020 at 20:04 Andon MitevAndon Mitev 1,5142 gold badges17 silver badges36 bronze badges 1
  • 1 What do you mean? What is your expected output here? – VLAZ Commented May 26, 2020 at 20:04
Add a ment  | 

5 Answers 5

Reset to default 9

Take the array of keys and map each to an entry of the key and the 5 value:

const keys = ['a', 'b', 'c'];
const obj = {
  ...Object.fromEntries(
    keys.map(key => [key, 5])
  ),
  d: 6
};

console.log(obj);

Something like this works:

const obj = {};
const value = 5;
['a', 'b', 'c'].forEach(key => obj[key] = value);

You can build a zip function which takes an array of keys and a array of values and returns an object where each key/value pair is taken from their respective index:

const zip =
  (ks, vs) =>
    ks.reduce((o, k, i) =>
      (o[k] = vs[i], o), {});

zip(['a', 'b', 'c'], [5, 5, 5]);
//=> {a: 5, b: 5, c: 5}

If you need to generate an array of 5:

Array(3).fill(5);
//=> [5, 5, 5]

Another solution could take a spreading of Object.assign with a spreaded array of objects.

const
    keys = ['a', 'b', 'c'],
    obj = { ...Object.assign(...keys.map(k => ({ [k]: 5 }))), d: 6 };
    
console.log(obj);

   function(item)
   {
      return  Object.keys(item).reduce((a, b) => ({ ...a, [b]:5 }),{});
   }
发布评论

评论列表(0)

  1. 暂无评论