Home > front end >  JavaScript - How do I dynamically assign a new key value pair to an object, using object-literal, an
JavaScript - How do I dynamically assign a new key value pair to an object, using object-literal, an

Time:09-21

I want to dynamically specify negative values as seen in this exact question.

Rules for unquoted JavaScript Object Literal Keys?

I want to also accomplish this using some method of dynamic bracket notation, using a string equivalent of a negative remainder (modulus operation).

bucketObj[key] reports undefined, since I have not pre set a key to store a corresponding value. How do I dynamically set a key of an object in either bracket notation, dot notation, or both?

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

CodePudding user response:

You can use Array#reduce with an object as the accumulator. Each time a new key is encountered, first set that property value to be an empty array.

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}

  • Related