我的array
为object
(rawData
)。 object
中的每个array
代表各种系列(即rawData = [(xi,y1i,y2i,..yni)]
)的x坐标和y坐标。我想将其转换为convertedData
的{{1}},其中array
仅代表一个系列(即object
)
object
干净地尝试此操作的Javascript方法是什么?
convertedData = [[(xi,y1i)], [(xi,y2i)]...[(xi,yni)]]
答案 0 :(得分:1)
这一切都取决于您认为最干净的东西。有几种编程策略,每种策略各有利弊。
这是一种函数式编程方法,该方法使用Array原型函数和ES6 Map
作为临时哈希来按x
值对数据进行分组。
const rawData = [{x: 1,y1:"1 y1 string",y2:"1 y2 string",y3:"1 y3 string",yn:"1 yn string",},{x: 2,y1:"2 y1 string",y2:"2 y2 string",y3:"2 y3 string", yn:"2 yn string", }];
const convertedData = Array.from(rawData.reduce(
(map, obj) => Object.keys(obj).filter(key => key != "x").reduce(
(map, key) => map.set(key, (map.get(key) || []).concat([[obj.x, obj[key]]])),
map
),
new Map
), ([name, data]) => ({name, data}));
console.log(convertedData);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:1)
这是外部数组上reduce
的一个很好的用例,然后循环遍历每个对象的条目。
let rawData = [{x: 1,y1:"1 y1 string", y2:"1 y2 string",y3:"1 y3 string",yn:"1 yn string",},{x: 2,y1:"2 y1 string", y2:"2 y2 string",y3:"2 y3 string",yn:"2 yn string",}];
let obj = rawData.reduce((o, item) => {
Object.entries(item).forEach(([key, val]) => {
if (key === 'x') return
if (o.hasOwnProperty(key)){
let data = o[key].data
data.push([data.length+1, val])
} else {
o[key] = {name: key, data: [[1, val]]}
}
})
return o
}, {})
// obj is an object, but you are only interested in the values:
console.log(Object.values(obj))
答案 2 :(得分:0)
虽然不漂亮,但确实可以解决问题。唯一真正令人讨厌的部分是Number(item [1] [0]),它将从[“ y2”,“ 1 y2字符串”]中剥离1
//Flatten the data
const y = rawData.map(item => {
return Object.entries(item).filter(entry => entry[0] !== 'x');
}).reduce((acc, curr) => acc.concat(curr), []);
//Create yheader array: ["y1", "y2"..., "yn"];
const yHeaders = [... new Set(y.map(item => item[0]))];
//for each y header, build the corresponding data object
const clean = yHeaders.map(targetHeader => {
return {
name: targetHeader,
data: y.filter(item => item[0] === targetHeader).map(item => [ Number(item[1][0]), item])
}
});