在 js 中将对象数组转换为值数组
要将对象数组转换为值数组,请在数组上调用 map()
方法,并在每次迭代时返回值,例如 arr.map(obj => obj.property)
。 map
方法将返回一个包含相应值的新数组。
const arrofobj = [
{id: 1, name: 'alice'},
{id: 2, name: 'bob'},
];
const arr = arrofobj.map(object => object.name);
console.log(arr); // 👉️ ['alice', 'bob']
我们传递给 array.map
方法的函数被数组中的每个元素(对象)调用。
在每次迭代中,我们访问特定属性的对象以获取值数组。
map()
方法返回一个新数组,其中包含回调函数返回的所有值。
map
方法不会改变原始数组,它返回一个新数组。
另一种方法是使用 array.foreach
方法迭代数组。
const arrofobj = [
{id: 1, name: 'alice'},
{id: 2, name: 'bob'},
];
const arr = [];
arrofobj.foreach(object => {
arr.push(object.name);
});
console.log(arr); // 👉️ ['alice', 'bob']
foreach
方法返回 undefined,所以我们必须声明一个变量来存储迭代数组的状态。
我们传递给方法的函数被数组中的每个元素(对象)调用。
最后一步是推动我们想要坚持的价值观。
对于这个用例,我们应该使用
map
方法,因为它更直接。 使用foreach
时,我们不得不声明一个中间变量来存储循环遍历数组的状态。
转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处
本文地址:
相关文章
do you understand javascript closures?
发布时间:2025/02/21 浏览次数:108 分类:javascript
-
the function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. a closure itself is a core concept in javascript, and being a core concept, it is naturally also a difficult one.
将 pandas dataframe 转换为 json
发布时间:2024/04/21 浏览次数:153 分类:python
-
本教程演示了如何将 pandas dataframe 转换为 json 字符串。
在 pandas 中加载 json 文件
发布时间:2024/04/21 浏览次数:105 分类:python
-
本教程介绍了我们如何使用 pandas.read_json()方法将一个 json 文件加载到 pandas dataframe 中。
将 numpy 数组转换为 pandas dataframe
发布时间:2024/04/21 浏览次数:111 分类:python
-
本教程介绍了如何使用 pandas.dataframe()方法从 numpy 数组生成 pandas dataframe。
如何将 pandas dataframe 转换为 numpy 数组
发布时间:2024/04/20 浏览次数:176 分类:python
-
本教程介绍如何将 pandas dataframe 转换为 numpy 数组的方法,例如 to_numpy,value 和 to_records
将 json 转换为 pandas dataframe
发布时间:2024/04/20 浏览次数:135 分类:python
-
本教程演示了如何使用 json_normalize()和 read_json()将 json 字符串转换为 pandas dataframe。
发布时间:2024/03/22 浏览次数:177 分类:javascript
-
通过 json.parse() 方法访问 javascript 中的 json 对象和数组可以有多种做法。可以使用点(.) 操作或括号对([]) 访问它。