我是 javaScript 新手,想處理以下陣列 -
var a=[
"John-100",
"Mark-120",
"John-50",
"Mark-130"
]
成以下格式——
a = {
"John": [100, 50],
"Mark": [120, 130]
}
但一直無法這樣做。任何幫助將不勝感激。蒂亞!
編輯 - 也歡迎任何其他可以將特定學生的分陣列合在一起的格式想法。
uj5u.com熱心網友回復:
這是實作您所描述的一種方法:
var a=[
"John-100",
"Mark-120",
"John-50",
"Mark-130"
]
function convertToSpecialObject() {
//setup the output as an empty object
const output = {};
// iterate through input array one element at a time
a.forEach(e => {
// split the current element by dividing it into part[0] before the dash
// and part[1] after the dash sign
const parts = e.split(/-/);
// now check the output object if it already contains a key for the part before the dash
if(!output[parts[0]]) {
// in this case, we don't have a key for it previously
// so lets set it up as a key with an empty array
output[parts[0]] = [];
}
// we must have already created a key or there is a key in existence
// so let's just push the part after the dash to the current key
output[parts[0]].push(parts[1]);
});
// work done
return output;
}
const b = convertToSpecialObject(a);
console.log(b);
uj5u.com熱心網友回復:
正如我所建議的那樣,字串拆分和陣列縮減 - 添加陣列映射,它是一行代碼
let a=["John-100","Mark-120","John-50","Mark-130"];
a=a.map(v=>v.split('-')).reduce((r,[n,m])=>(r[n]=[...r[n]||[], m],r),{});
console.log(JSON.stringify(a));
唯一正確結果的答案...一個 NUMBERS 陣列
uj5u.com熱心網友回復:
你可以通過使用來實作這一點reduce and split method
var a=[
"John-100",
"Mark-120",
"John-50",
"Mark-130"
]
const b = a.reduce((acc, val) => {
const _split = val.split('-');
const name = _split[0]
if(acc && acc[name]) {
acc[name].push( _split[1])
} else {
acc[name] = [ _split[1]]
}
return acc;
}, {});
console.log(b)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/494107.html
標籤:javascript 节点.js 数组 目的
上一篇:如何創建條件測驗?
下一篇:將陣列陣列轉換為單個物件陣列
