在javaScript中将数据处理成所需的格式



我是JavaScript新手,想处理以下数组-

var a = [
"John-100",
"Mark-120",
"John-50",
"Mark-130"
]

将转换成以下格式-

a = {
"John": [100, 50],
"Mark": [120, 130]
}

但是我不能这样做。如有任何帮助,我将不胜感激。

Edit -任何其他可以将特定学生的分数分组在一起的格式也是欢迎的。

这里有一种方法可以实现你所描述的:

var a=[
"John-100",
"Mark-120",
"John-50",
"Mark-130"
]
function convertToSpecialObject(input) {
//setup the output as an empty object
const output = {};

// iterate through input array one element at a time
input.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(Number(parts[1]));
});

// work done
return output;
}
const b = convertToSpecialObject(a);
console.log(b);

您可以通过使用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)

您可以通过使用Array.forEach()方法和String.split()方法以非常简单的方式实现它。

Live Demo:

var a = [
"John-100",
"Mark-120",
"John-50",
"Mark-130"
];
const obj = {};
a.forEach(element => {
if (!obj[element.split('-')[0]]) {
obj[element.split('-')[0]] = [];
}
obj[element.split('-')[0]].push(element.split('-')[1])
});
console.log(obj);

用简单的方法

const input = [
"John-100",
"Mark-120",
"John-50",
"Mark-130"
];

const getCustomObject = (arr) => {
const obj = {};
for (let i = 0; i < arr.length; i++) {
const split = arr[i].split('-'); //spliting with '-'
if (obj[split[0]]) {
//push to existing array
obj[split[0]].push(split[1]);
} else {
obj[split[0]] = []; //initilize array if no member
obj[split[0]].push(split[1]);
}
};
return obj;
}
console.log(getCustomObject(input));

现在数字不是数值,可以用parseIntparseFloat来实现

正如我所建议的,字符串分割和数组减少-添加在数组映射中,它是一行代码

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]}),{});
console.log(JSON.stringify(a));

唯一正确的答案是…数组

相关内容

  • 没有找到相关文章