返回

万物皆可转换 -- 掌握对象、数组、Map、JSON之间的相互转换小技巧

前端

前言

在日常开发中,我们经常会遇到需要将一种数据结构转换为另一种数据结构的情况。例如,我们需要将对象转换为数组以便在前端展示,或者需要将数组转换为对象以便存储到数据库中。这些转换操作通常需要我们编写大量的代码,并且很容易出错。为了简化这些转换操作,我们可以使用一些内置的方法或第三方库来实现。

ES5 中 对象 与数组,JSON 之间的相互转换

对象转换为数组

在ES5中,我们可以使用Object.keys()方法将对象的键名转换为数组,然后使用map()方法将键名转换为对应的键值,最后使用values()方法将键值转换为数组。

const person = {
  name: 'John Doe',
  age: 30,
  city: 'New York'
};

const keys = Object.keys(person);
const values = keys.map(key => person[key]);

console.log(keys); // ['name', 'age', 'city']
console.log(values); // ['John Doe', 30, 'New York']

数组转换为对象

在ES5中,我们可以使用reduce()方法将数组转换为对象。

const numbers = [1, 2, 3, 4, 5];

const obj = numbers.reduce((acc, cur, idx) => {
  acc[`number${idx + 1}`] = cur;
  return acc;
}, {});

console.log(obj); // { number1: 1, number2: 2, number3: 3, number4: 4, number5: 5 }

JSON 转换

在ES5中,我们可以使用JSON.stringify()方法将对象转换为JSON字符串,然后使用JSON.parse()方法将JSON字符串转换为对象。

const person = {
  name: 'John Doe',
  age: 30,
  city: 'New York'
};

const json = JSON.stringify(person);
const obj = JSON.parse(json);

console.log(json); // '{"name":"John Doe","age":30,"city":"New York"}'
console.log(obj); // { name: 'John Doe', age: 30, city: 'New York' }

ES6 中 Map 与对象、数组,JSON 之间的相互转换

Map 转为对象

const map = new Map([
  ['name', 'John Doe'],
  ['age', 30],
  ['city', 'New York']
]);

const obj = Object.fromEntries(map);

console.log(obj); // { name: 'John Doe', age: 30, city: 'New York' }

对象 转为 Map

const person = {
  name: 'John Doe',
  age: 30,
  city: 'New York'
};

const map = new Map(Object.entries(person));

console.log(map); // Map { 'name' => 'John Doe', 'age' => 30, 'city' => 'New York' }

Map 转为数组

const map = new Map([
  ['name', 'John Doe'],
  ['age', 30],
  ['city', 'New York']
]);

const arr = [...map];

console.log(arr); // [['name', 'John Doe'], ['age', 30], ['city', 'New York']]

数组 转为 Map

const arr = [['name', 'John Doe'], ['age', 30], ['city', 'New York']];

const map = new Map(arr);

console.log(map); // Map { 'name' => 'John Doe', 'age' => 30, 'city' => 'New York' }

JSON 转换

在ES6中,我们可以使用JSON.stringify()方法将对象转换为JSON字符串,然后使用JSON.parse()方法将JSON字符串转换为对象。

const person = {
  name: 'John Doe',
  age: 30,
  city: 'New York'
};

const json = JSON.stringify(person);
const obj = JSON.parse(json);

console.log(json); // '{"name":"John Doe","age":30,"city":"New York"}'
console.log(obj); // { name: 'John Doe', age: 30, city: 'New York' }

总结

在这篇文章中,我们介绍了如何在ES5和ES6中将对象、数组、Map和JSON相互转换。我们提供了清晰的代码示例,以便您轻松理解和应用这些转换方法。希望这些知识能够对您的开发工作有所帮助。