简体   繁体   中英

How to create a pair from two or three keys in an object to an array in Javascript

I have the following JavaScript object:

alphabet_num = {
  "alphabet": [
    "A",
    "B",
    "C",
    "D",
    "E",
    "F"
  ],
  "numbers": [
    "1",
    "2",
    "3",
    "4",
    "5",
    "6"
  ],
  "roman": [
    "I",
    "II",
    "III",
    "IV",
    "V",
    "VI"
  ]
};

I want to convert this into a value pair array like this:

alphabet_num = [
                ["A","1","I"],
                ["B","2","II"],
                ["C","3","III"],
                ["D","4","IV"],
                ["E","5","V"],
                ["F","6","VI"]
               ]

I tried using the Object.values and Object.entries to figure this out but in vain.

alphabet_num = {
  "alphabet": [
    "A",
    "B",
    "C",
    "D",
    "E",
    "F"
  ],
  "numbers": [
    "1",
    "2",
    "3",
    "4",
    "5",
    "6"
  ],
  "roman": [
    "I",
    "II",
    "III",
    "IV",
    "V",
    "VI"
  ]
};

var result = Object.keys(alphabet_num).map(function(key) {
  return alphabet_num[key];
});
var tempArr = new Array(result[0].length).fill("")
var final = tempArr.map((el, index) => [result[0][index],result[1][index],result[2][index]])

console.log(final);

Hope this help

let alphabet_num = {
  alphabet: ["A", "B", "C", "D", "E", "F"],
  numbers: ["1", "2", "3", "4", "5", "6"],
  roman: ["I", "II", "III", "IV", "V", "VI"]
};

let finalArr = [];
alphabet_num.alphabet.map((eachElement, index) => {
  let arr = [];
  Object.keys(alphabet_num).map(item => arr.push(alphabet_num[item][index]) );
  finalArr.push(arr);
});

console.log(finalArr);  // [ ["A","1","I"], ["B","2","II"], ["C","3","III"], ["D","4","IV"], ["E","5","V"], ["F","6","VI"] ]

You can make use of map to achieve the task:

 var alphabet_num = { "alphabet": [ "A", "B", "C", "D", "E", "F" ], "numbers": [ "1", "2", "3", "4", "5", "6" ], "roman": [ "I", "II", "III", "IV", "V", "VI" ]}; var result = alphabet_num.alphabet.map((k,i)=>[k,alphabet_num.numbers[i], alphabet_num.roman[i]]); console.log(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM