【问题标题】:Map array return key in a string format in JavaScript在JavaScript中以字符串格式映射数组返回键
【发布时间】:2022-01-16 06:50:29
【问题描述】:

我有一个从给定数组映射和创建新数组的函数。在我将数组映射到key: "value" 之后,但映射函数返回给我"key": "value"

如何获取或映射非字符串格式的键?

let categories_name = [{ name: "test", prov_id: "f34f43"}, { name : "test1", prov_id: "233edd3"}]
  .map(v => v.prov_id)
  .filter((item, index, arr) => arr.indexOf(item) === index);

结果是这样的

["f34f43","233edd3"]

现在我想为每个值添加一个键(名称)并转换为一个对象

let newArray = categories_name.map(value => ({name: value}));

这是结果:

[ { "name": "f34f43" }, { "name": "233edd3" }]

但我需要这样,键不像字符串。

[ { name: "f34f43" }, { name: "233edd3" }]

【问题讨论】:

  • 你“需要”的东西和你得到的东西是完全一样的。这似乎是XY problem
  • { "name": "f34f43" }{ name: "f34f43" } 是相同的。
  • 为什么首先需要name 而不是"name"?它们在 JS 对象中是一样的
  • Javascript 对象中的所有键都是字符串。该语言只允许在不需要时省略引号。如果您需要连字符等字符,{ 'fun-key': 'f34f43' } 适用于对象键
  • 这两件事之间没有区别。当键里面有奇怪的字符时,你只需要引号。如果你在你的数组上使用 JSON.stringify,它们都会被引用,这是唯一真正重要的时候。

标签: javascript javascript-objects


【解决方案1】:

在 JavaScript 对象中,所有键都是字符串。所以以下内容完全相同/相同:

{ "key": "value" }
{ key: "value" }

// Hence your example is identical as well:
{ "name": "f34f43" }
{ name: "f34f43" }

【讨论】:

  • 谢谢我意识到这是 Vue 将键转换为字符串,如果我在组件中使用,它可以正常工作。谢谢!
【解决方案2】:

当您运行下面的代码时,您会看到即使是您的原始输入在打印时也具有"key": "value" 形式的对象属性:

let categories_name = [{ name: "test", prov_id: "f34f43"},{ name : "test1", prov_id: "233edd3"}]
console.log('source:', categories_name)


let ids = categories_name.map(v => v.prov_id)
  .filter((item, index, arr) => arr.indexOf(item) === index);
console.log('ids:', ids)


let newArray = categories_name.map(value => ({name: value}));
console.log('newArray:', newArray)

That's just the standard JSON representation,如果你使用JSON.stringify,你会得到什么。

如果你真的需要字符串表示看起来像 ES5 语法,请参阅my answer to the above linked SO question。根据这个答案,下面我使用来自JSON5 库的JSON5.stringify,它具有与内置JSON 对象的兼容接口:

// if node, import 'json5' here, as opposed to 
// the HTML script tag this example relies on

let categories_name = [{ name: "test", prov_id: "f34f43"},{ name : "test1", prov_id: "233edd3"}]
console.log('source:', JSON5.stringify(categories_name))


let ids = categories_name.map(v => v.prov_id)
  .filter((item, index, arr) => arr.indexOf(item) === index);
console.log('ids:', JSON5.stringify(ids))


let newArray = categories_name.map(value => ({name: value}));
console.log('newArray:', JSON5.stringify(newArray))
<script src="https://unpkg.com/json5@^2.0.0/dist/index.min.js"></script>

【讨论】:

  • "当您运行下面的代码时,您会看到即使您的原始输入在打印时也具有“key”:“value”形式的对象属性:” StackSnippets 提供的控制台。控制台可以随意表示对象 - Firefox 控制台,例如 does not show any quotes。控制台中应该显示什么没有标准,键是否显示为引号以及使用哪些引号显示它也没有任何区别。
  • @VLAZ 每个人都在和我争论很有趣。即使我同意你的观点,这也是我回答的前言所做的。无论如何,提问者显然是在谈论序列化或印刷格式。正如您甚至建议的那样,某些人或项目(例如 Firefox)更喜欢不带引号的形式。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-15
  • 2012-01-23
  • 1970-01-01
  • 2018-01-03
  • 2020-12-12
相关资源
最近更新 更多