如何将一个对象数组插入另一个数组?
How to insert a array of objects into another array?
我从Api得到的数据是一个数组,如下:
var arrayX = [{key: "GET", doc_count: 12},
{key: "POST", doc_count: 381}]
我想在图表中显示此键 'key' 和 'doc_cont' 的值。
图表格式如下:
" ....
data: [{value: 'Doc_count' information of 'POST' key information will come in this field, name: 'POST'},
{value: put, name: 'PUT'},
{value: get, name: 'GET'}]
..."
当我想给'arrayX'中的'doc_count'赋值时,返回'undefined'。
for (var i = 0; i <= arrayX.length; i++) {
if (arrayX[i].key == 'POST') {
var post = arrayX[i].doc_count;
}
else if (arrayX[i].key == 'PUT') {
var put = arrayX[i].doc_count;
}
else if (arrayX[i].key == 'GET') {
var get = arrayX[i].doc_count;
}
}
我该如何解决这种情况?
我希望我的问题清楚。
你很接近,这里唯一的问题是你的循环条件。
改变这个:
for (var i = 0; i <= arrayX.length; i++)
为此:
for (var i = 0; i < arrayX.length; i++)
我已将 <=
更改为 <
。
如果您使用 <=
,您将获得 0,1 和 2 的索引,并且由于您在 arrayX
中没有索引 2,您将获得异常(数组索引从 0 开始)。
您可以在 Arrays index
中阅读更多内容
据我了解,您想转换以下结构的数组:
[{key: "GET", doc_count: 12}, {key: "POST", doc_count: 381}]
进入:
[{name: "GET", value: 12}, {name: "POST", value: 381}]
为此,Array.prototype.map()
可能是更具描述性的方式。
来自官方docs:
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
var arrayX = [{
key: "GET",
doc_count: 12
}, {
key: "POST",
doc_count: 381
}]
var chartData = arrayX.map((item) => {
return {
name: item.key,
value: item.doc_count
}
});
console.log(chartData)
console.log(arrayX)
我从Api得到的数据是一个数组,如下:
var arrayX = [{key: "GET", doc_count: 12},
{key: "POST", doc_count: 381}]
我想在图表中显示此键 'key' 和 'doc_cont' 的值。 图表格式如下:
" ....
data: [{value: 'Doc_count' information of 'POST' key information will come in this field, name: 'POST'},
{value: put, name: 'PUT'},
{value: get, name: 'GET'}]
..."
当我想给'arrayX'中的'doc_count'赋值时,返回'undefined'。
for (var i = 0; i <= arrayX.length; i++) {
if (arrayX[i].key == 'POST') {
var post = arrayX[i].doc_count;
}
else if (arrayX[i].key == 'PUT') {
var put = arrayX[i].doc_count;
}
else if (arrayX[i].key == 'GET') {
var get = arrayX[i].doc_count;
}
}
我该如何解决这种情况? 我希望我的问题清楚。
你很接近,这里唯一的问题是你的循环条件。
改变这个:
for (var i = 0; i <= arrayX.length; i++)
为此:
for (var i = 0; i < arrayX.length; i++)
我已将 <=
更改为 <
。
如果您使用 <=
,您将获得 0,1 和 2 的索引,并且由于您在 arrayX
中没有索引 2,您将获得异常(数组索引从 0 开始)。
您可以在 Arrays index
中阅读更多内容据我了解,您想转换以下结构的数组:
[{key: "GET", doc_count: 12}, {key: "POST", doc_count: 381}]
进入:
[{name: "GET", value: 12}, {name: "POST", value: 381}]
为此,Array.prototype.map()
可能是更具描述性的方式。
来自官方docs:
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
var arrayX = [{
key: "GET",
doc_count: 12
}, {
key: "POST",
doc_count: 381
}]
var chartData = arrayX.map((item) => {
return {
name: item.key,
value: item.doc_count
}
});
console.log(chartData)
console.log(arrayX)