美文网首页
js 将对象转换为数组

js 将对象转换为数组

作者: 砚婉儿 | 来源:发表于2024-07-30 11:48 被阅读0次
用到的方法有:Object.keys()、Object.values() 、Object.entries() 和 map()混合、for...in

1,Object.keys() 方法:

const obj = { a: 1, b: 2, c: 3 };
const arr = Object.keys(obj);
console.log(arr); // 输出 [a, b, c]

2,Object.values() 方法:

const obj = { a: 1, b: 2, c: 3 };
const arr = Object.values(obj);
console.log(arr); // 输出 [1, 2, 3]

3,Object.entries() 和 map(): 将对象的键值对转换为数组的元素

// 情况一:
const obj = { a: 1, b: 2, c: 3 };
const arr = Object.entries(obj).map(([key, value]) => [key, value]);
console.log(arr); // 输出 [['a', 1], ['b', 2], ['c', 3]]
// 情况二:
const data = {
  a: { name: "a", index: 7 },
  b: { name: "b", index: 3 },
  c: { name: "c", index: 5 }
};
 
// 将对象转换为数组
const dataArray = Object.entries(data).map(([key, value]) => ({
  key,
  ...value,
}));
 
/* 输出:
[
    { key: "a", name: "a", index: 7 },
    { key: "b", name: "b", index: 3 },
    { key: "c", name: "c", index: 5 },
];
 */

4,使用for...in循环迭代对象属性:

const obj = { a: 1, b: 2, c: 3 };
const arr = [];
for (const key in obj) {
  if (obj.hasOwnProperty(key)) {
    arr.push(obj[key]);
  }
}
console.log(arr); // 输出 [1, 2, 3]

参考链接:134154442

相关文章

网友评论

      本文标题:js 将对象转换为数组

      本文链接:https://www.haomeiwen.com/subject/ofkghjtx.html