JavaScript - 如何使用对象字面量和括号表示法将新的键值对动态分配给对象,并在一行中展开语法?

JavaScript - How do I dynamically assign a new key value pair to an object, using object-literal, and bracket notation, spread syntax in a one-liner?

我想动态指定负值,如这个确切问题中所示。

Rules for unquoted JavaScript Object Literal Keys?

我还想使用某种动态括号表示法来完成此操作,使用与负余数等效的字符串(模运算)。

bucketObj[key]报undefined,因为我没有预先设置key来存储对应的值。如何在括号表示法、点表示法或两者中动态设置对象的键?

 function toDigitBuckets(array, radix) {
    let bucket = JSON.parse(JSON.stringify([...Array(radix).fill([])]));
    let bucketObj = Object.assign(bucket);
    array.forEach(val => { let key = String.toString(val % 10); bucketObj[key].push(val) });
    return bucket; 
  }
  
  let array = [-7, -49, 84, 39, -31, 95, 7, -8, -13, -32, 93, 40, -81, -30, -57, -57, 49, 66, -64, 42, 35, 29, -57, 41, 93, 34, -45, -15, 51, 16, 97, -88, 52, -69, 56, -16, -91, 51, 10, -21, 80, 78, -5, 18, -20, -98, 72, -94, 11, -83, -31, 13, -21, 39, -47, 8, -98, 95, 52, -18, 77, -11, -38, -46, -98, 48, -45, -4, 76, -32, -81, 67, -82, 9, -60, -20, 0, 33, -12, 77, 65, 45, -22, 99, -47, -83, -81, 10, -99, 16, 23, 5, -57, 89, -62, 9, -16, 79, 5, -2];
  
  let radix = 10;
  console.log(JSON.stringify(toDigitBuckets(array, radix)));

您可以将 Array#reduce 与对象一起用作累加器。每次遇到新键时,首先将 属性 值设置为空数组。

function toDigitBuckets(array, radix) {
  return array.reduce((acc, curr) => 
    ((acc[curr % radix] ??= []).push(curr), acc), {});
}
let array = [-7, -49, 84, 39, -31, 95, 7, -8, -13, -32, 93, 40, -81, -30, -57, -57, 49, 66, -64, 42, 35, 29, -57, 41, 93, 34, -45, -15, 51, 16, 97, -88, 52, -69, 56, -16, -91, 51, 10, -21, 80, 78, -5, 18, -20, -98, 72, -94, 11, -83, -31, 13, -21, 39, -47, 8, -98, 95, 52, -18, 77, -11, -38, -46, -98, 48, -45, -4, 76, -32, -81, 67, -82, 9, -60, -20, 0, 33, -12, 77, 65, 45, -22, 99, -47, -83, -81, 10, -99, 16, 23, 5, -57, 89, -62, 9, -16, 79, 5, -2];
let radix = 10;
console.log(toDigitBuckets(array, radix));
.as-console-wrapper{max-height:100%!important;top:0}