Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
109 views
in Technique[技术] by (71.8m points)

javascript - JS Turn an array into Object with property key/value

i was coding and i found this problem, the goal is turn the items array into a object with property key/value, counting the items that appear more than once like that:

{
  cookie:{
    MILK: 1,
    CHOCOLATE: 2,
    DELUXE: 1
  },
  bread:{
    BIG: 2
  },
  beer:{
    NEW: 1,
    OLD: 1
  }
}

I tried this code below

const items = [
  "cookie-MILK",
  "cookie-CHOCOLATE",
  "cookie-CHOCOLATE",
  "cookie-DELUXE",
  "bread-BIG",
  "bread-BIG",
  "beer-NEW",
  "beer-OLD"
]
let newArray = [];

items.forEach((e) => {
  let splitArray = e.split("-");
  newArray.push([splitArray[0], splitArray[1]]);
});


let result = newArray.reduce((acc, val) => {
  if (!acc[val[0]] && !acc[val[1]] ) acc[val[0]] = {
     [val[1]]: 1,
  };
   else acc[val[0]][val[1]]++;
  return acc;
}, {});

But this code returns it and i don't know how to solve this question

{
  cookie:{
    MILK: 1,
    CHOCOLATE: NaN,
    DELUXE: NaN
  },
  bread:{
    BIG: 2
  },
  beer:{
    NEW: 1,
    OLD:  NaN
  }
}
question from:https://stackoverflow.com/questions/65921320/js-turn-an-array-into-object-with-property-key-value

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You could take a logical nullish assignment ??= for assigning an object or zero and increment the value.

const
    items = ["cookie-MILK", "cookie-CHOCOLATE", "cookie-CHOCOLATE", "cookie-DELUXE", "bread-BIG", "bread-BIG", "beer-NEW", "beer-OLD"],
    result = items.reduce((acc, val) => {
        const [left, right] = val.split("-");
        (acc[left] ??= {})[right] ??= 0;
        acc[left][right]++;
        return acc;
    }, {});

console.log(result);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...