gpt4 book ai didi

javascript - JS : Convert a specific values from an object into an array?

转载 作者:行者123 更新时间:2023-12-03 06:32:31 26 4
gpt4 key购买 nike

我有一个对象:

var obj = 
[
{
"value": "aep",
"label": "AEP"
},
{
"value": "cap",
"label": "CAP"
},
{
"value": "casl",
"label": "CASL"
} ]

我只想将标签的值转换为数组,以便最终结果是:

["AEP", "CAP", "CASL"]

如何仅获取数组中转换的标签值?

最佳答案

首先:obj不是一个对象,它是一个数组,因为父括号是[]而不是{}。不过,我会保持名称不变。这可能会给您带来一些困惑,例如

var object = {};
var array = [];
var arrayOfObjects = [{},{},{}];
var objectOfArrays = {array1: [],array2: [],array3: []};

要循环数组,您可以使用 for 循环:

// new array
var newArray = [];
// iterates over each index in the array
for(var i=0; i<obj.length; i++) {
// Access the specific index, then access its `label` property
// Push into `newArray`
newArray.push(obj[i].label);
}

console.log(newArray);

代码笔:http://codepen.io/theblindprophet/pen/RRxVba

关于javascript - JS : Convert a specific values from an object into an array?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38385022/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com