Skip to content
Advertisement

How do I loop through similar key value pairs(a0,a1,a2) in JavaScript object and generate a new array without the number in the key(a)?

What I have
1.keys: similar key name(such as a0,a1,a2)
2.obj: a lot of similar key-value pairs in one object
3.number: the times similar key-value pairs looped in obj1)
4.arr: a array without the number in the key(only keep “a”, no “a0″,”a1″,”a2”)

p.s. “aa”,”bb”,”cc” are examples, the value can be anything

let keys = ["javascript","java","python","php"];
let number = 3;
let obj = {
javascript0:"a",java0:"b",python0:"c",php0:"d",
javascript1:"aa",java1:"bb",python1:"cc",php1:"dd",
javascript2:"aaa",java2:"bbb",python2:"ccc",php2:"ddd",
}

What I want

let arr = [
{javascript:"a",java:"b",python:"c",php:"d"},
{javascript:"aa",java:"bb",python:"cc",php:"dd"},
{javascript:"aaa",java:"bbb",python:"ccc",php:"ddd"}
]

How can I get array?

Advertisement

Answer

let keys = ["javascript", "java", "python", "php"];

let obj = {
  javascript0: "a0",
  java0: "b0",
  python0: "c0",
  php0: "d0",
  javascript1: "a1",
  java1: "b1",
  python1: "c1",
  php1: "d1",
  javascript2: "a2",
  java2: "b2",
  python2: "c2",
  php2: "d2",
};

let result = [];
let number = 3;
for (i = 0; i < number; i++) {
  let _r = {};
  keys.forEach((item) => {
    if (obj.hasOwnProperty(`${item}${i}`)) {
      _r[item] = obj[`${item}${i}`];
    }
  });
  result.push(_r);
}
console.log(result);
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement