[英]I want to dynamically create arrays of object values based on their keys from an array of similar objects
Here's my JavaScript array of objects: 这是我的JavaScript对象数组:
inventoryArray = [
{name: 'pizza', category: 'food', unique: 'no', amount: 12}
{name: 'bow', category: 'weapon', unique: 'no', amount: 1}
{name: 'pizza', category: 'food', unique: 'yes', amount: 1}
]
They all have the same keys and most have different values. 它们都具有相同的键,并且大多数具有不同的值。
I want to create an array of values based on keys dynamically that looks like this: 我想基于键动态创建一个值数组,如下所示:
values = [
['pizza', 'bow', 'pizza'] // name
['food', 'weapon', 'food'] // category
['no', 'no', 'yes'] //unique
[12, 1, 1] // amount
// TODO only add distinct values:
// i.e. first array would be ['pizza', 'bow']
]
Closest I've gotten is: 我最近得到的是:
const keys = [];
const values = [];
for(let i = 0; i < inventoryArray.length; i++){
keys[i] = Object.keys(inventoryArray[i]);
}
for(let i = 0; i < keys[0].length; i++) {
const value = [];
for(let j = 0; j < inventoryArray.length; j++) {
value[j] = inventoryArray[j][keys[j][i]];
}
values[i] = value;
}
Yeah, I know it's ugly. 是的,我知道这很丑。
That keys[0]
in the second for loop is not really dynamic. 第二个for循环中的
keys[0]
并不是真正动态的。 Right? 对?
I'm still pretty new at JavaScript and I tried playing around with the map method for arrays, but couldn't get it to create them all dynamically. 我在JavaScript上还很陌生,我尝试使用数组的map方法,但是无法动态创建它们。 Just one by one:
一一:
const names = inventoryArray.map(a => a.name);
Thanks in advance! 提前致谢!
Create an array of the props you want in the correct order. 以正确的顺序创建所需道具的数组。 Use nested
Array.map()
calls to create the matrix. 使用嵌套的
Array.map()
调用创建矩阵。 You can use a Set , to make the values distinct. 您可以使用Set来使值区分。
const inventoryArray = [{"name":"pizza","category":"food","unique":"no","amount":12},{"name":"bow","category":"weapon","unique":"no","amount":1},{"name":"pizza","category":"food","unique":"yes","amount":1}] const props = ['name', 'category', 'unique', 'amount'] const result = props.map(p => [...new Set(inventoryArray.map(o => o[p]))] ) console.log(result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.