我想从对象数组中检索某些属性,并将其存储在数组中。
数据结构如下,
object_arr [{…}]0:
first_property: "color"
id: 25
x: 10
y: 50
z: 56
_proto__: Objectlength: 1__proto__: Array(0)
我想检索x、y和z值,这样输出应该像下面一样
(3) [10, 50, 56]
0: 10
1: 50
2: 56
length: 3
__proto__: Array(0)
so final_output[0] should give me 10, final_output[1] should give me 50 and final_output[2] should give 56
我试过什么?
let final_output = object_arr.map(m => {
return [
m.x,
m.y,
m.z
]
});
的最终输出如下
final_output [Array(3)]
0: (3) [10, 50, 56]
length: 1
the expected output is as below,
final_output (3) [10, 50, 56]
0: 10
1: 50
2: 56
length: 3
我该怎么解决这个问题。有人能帮我做这个吗。谢谢
这样做:
let object_arr = { first_property: "color", id: 25, x: 10, y: 50, z: 56}
let final_output = [object_arr.x, object_arr.y, object_arr.z];
这很简单。我认为您的困惑源于试图将输入数组作为一个整体进行处理。如果您只需要第一个元素中的数据,则不需要map
。只需使用[0]
:直接寻址即可
let object_arr = [{ first_property: "color", id: 25, x: 10, y: 50, z: 56}]
let final_output = [object_arr [0] .x, object_arr [0] .z, object_arr [0] .z];
console .log (final_output)
如果您的数组只包含一个对象,您可以直接将其属性添加到数组中,如下所示:
const object_arr = [{first_property:"color",id:25,x:10,y:50,z:56}];
const [{x, y, z}] = object_arr; // use destructuring to get the object keys from the array
const res = [x, y, z]; // create an array containing x, y, z properties
console.log(res);
如果您的数组可以包含多个对象,则可以通过将属性映射到一个数组来使用.flatMap()
,然后该数组将变成一个更大的结果数组。这样,(所有对象的(所有x
、y
和z
属性都将映射到一个更大的输出数组:
const object_arr = [{first_property:"color",id:25,x:10,y:50,z:56}];
const res = object_arr.flatMap(o => [o.x, o.y, o.z]);
console.log(res);
您可以清楚地看到:final_output [Array(3)]
0: (3) [10, 50, 56]
其为阵列的阵列。因此,要获得值10,您必须执行以下操作:final_output[0][0].
或output=final_output[0];
然后output[0]