javascript – Splitting an object into two JS parts

Question:

There is:

let obj = {"00:00": 1, "00:05": 4, "00:10": 7, "00:15": 5}

I need to split it into two parts, let's say 00:10 so that it looks like this:

{"00:00": 1, "00:05": 4}
{"00:10": 7, "00:15": 5}

Answer:

One way to do this is:

const obj = {"00:00": 1, "00:05": 4, "00:10": 7, "00:15": 5}
const result1 = {}
const result2 = {}

Object.keys(obj).forEach(key => {
  const targetNum = Number(key.slice(-2))
  if (targetNum >= 10) {
    result2[key] = obj[key] 
  } else {
    result1[key] = obj[key] 
  }
  // или
  // ;(targetNum >= 10 ? result2 : result1)[key] = obj[key]
})

console.log(result1, result2)
// {"00:00": 1, "00:05": 4}
// {"00:10": 7, "00:15": 5}
Scroll to Top