javascript - how to change the array format to the object format?
问题描述
How to use javascript to change the array to the object format? Thanks!
[ "16-282", "16-311", "16-320", "17-275", "17-276" ]
object format:</p>
[{
id: 16,
Options: [282, 311, 320],
},
{
id: 17,
Options: [275, 276],
}]
My Code:
test() {
var option = ["16-282", "16-311", "16-320", "17-275", "17-276"];
var finalResult = option.map((item, index) => ({id: item, Options: item, }));
console.log(finalResult);
},
解决方案
Lets start with your code:
var finalResult = option.map((item, index) => ({id: item, Options: item, }));
Here you are using .map
. It will return an array of n
length with parsed output.
Based on your output, you need to group the values based on part that is before -
. This can be done in many ways, but I'll use for
as its easy to understand:
Idea:
- Create an object to hold groups. Object and not array as Objects are key-value pair structure. So your groupId would be key and value will be the value to store.
- Now loop over the
option
array.- For every iteration, split
item
using hyphen(-
). First part is your key and second is your value. - Check if this key exists in
group
. If yes, push current value to theOptions
array. - If it does not exists, initialize it with default structure:
{ id: groupKey, Options: [ groupValue ] }
- For every iteration, split
Sample:
var option = ["16-282", "16-311", "16-320", "17-275", "17-276"];
var groups = {};
for (var i = 0; i< option.length; i++) {
var parts = option[i].split('-');
var groupKey = parts[0];
var groupValue = parts[1];
// Check if the groupKey exists in group
if (groups[ groupKey ] !== undefined) {
groups[ groupKey ].Options.push(groupValue)
} else {
groups[ groupKey ] = { id: groupKey, Options: [ groupValue ] }
}
}
console.log(groups)
Now that you have groups, you just need to loop over this object and make an array.
An accumulation of above grouping idea and creating array is as follows:
var option = ["16-282", "16-311", "16-320", "17-275", "17-276"];
const groups = option.reduce((acc, item) => {
const [ id, value ] = item.split('-');
acc[ id ] = acc[ id ] || { id, Options: [ ]};
acc[ id ].Options.push(value);
return acc;
}, {});
const result = Object.values(groups);
console.log(result)
.as-console-wrapper {
top: 0;
max-height: 100vh!important;
}