我需要将一个对象数组转换为另一个对象数组但转置。这是 highcharts 接受数组的形式。
我需要从
var n0 = [{
"a": 1,
"b": 4
}, {
"a": 2,
"b": 6
}, {
"a": 3,
"b": 8
}]
至
var n1 = [{
"name": "a",
"data": [1, 2, 3]
}, {
"name": "b",
"data": [4, 6, 8]
}];
如何更改
var input = [{
"date": "JAN",
"category": "abc",
"thevalue": 5
}, {
"date": "JAN",
"category": "xyz",
"thevalue": 4
}, {
"date": "FEB",
"category": "abc",
"thevalue": 9
}, {
"date": "FEB",
"category": "xyz",
"thevalue": 10
}]
至
var output = [{
"name": "abc",
"data": [5,9]
}, {
"name": "xyz",
"data": [4, 10]
}];
可以用相同的功能来完成吗?我读过两本 javascript 书籍,但不知何故,这些谜题远远超出了我的能力。我什至不知道从哪里开始学习。我想我可以重新阅读有关对象和数组的章节,问题是这些示例非常基础。
最佳答案
解决此问题的一个简单方法是记住您使用的每个键都存在于输入数组的每个条目中。使用Object.keys
获取任何这些对象的所有键的数组将为您提供名称
列表。从那里,迭代该数组并继续使用 .map
选择您感兴趣的特定键值。
请注意,如果数组为空,则会抛出错误。如果遇到这种特殊情况,您可以享受提前返回的条件。
如果您对我使用的语法有任何疑问,请随时要求澄清。
var n0 = [{
"a": 1,
"b": 4,
"c": 5
}, {
"a": 2,
"b": 6,
"c": 4
}, {
"a": 3,
"b": 8,
"c": 10
}]
function transposeObject(array) {
const newArr = [] // an empty array I make to store my values that I will eventually return
const arrayOfKeys = Object.keys(array[0]) // selecting the first element in the array. Taking the keys as an array
arrayKeys.forEach(name => {
const newObj = { name }; // new object. I insert the name to start.
const arrayOfNumbersByKeyName = array.map(object => object[name]) // create new array that is only compromised of the value from object[name], where name is a variable representing a key from arrayKeys
newObj.data = arrayOfNumbersByKeyName // insert my newly created array into newObject under the key 'data'
newArr.push(newObj) // push my fully constructed array into my newArr that I initialized at the top of the function
});
return newArr
}
console.log(transposeObject(n0))
更新:
您似乎正在尝试获取与category
中的键相关的每个值。抱歉,但是没有“简单”的方法来解决这个问题,除非你想编写一个非常长的算法。
一种方法是获取键的所有可能值,然后每次仅针对特定类别名称进行过滤
。
var input = [{
"date": "JAN",
"category": "abc",
"thevalue": 5
}, {
"date": "JAN",
"category": "xyz",
"thevalue": 4
}, {
"date": "FEB",
"category": "abc",
"thevalue": 9
}, {
"date": "FEB",
"category": "xyz",
"thevalue": 10
}]
function generateGraphData(array) {
const newArr = []
const arrayOfCategories = array.map(object => object.category)
const setOfCategories = new Set(arrayOfCategories)
for (const category of setOfCategories) {
const filteredCategories = array.filter(obj => obj.category === category)
const graphData = filteredCategories.map(obj => obj.thevalue)
newArr.push({ name: category, data: graphData})
}
return newArr
}
const data = generateGraphData(input)
console.log(data)
关于javascript - 将对象数组转换为转置对象数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50921263/