以 JavaScript 中的字符串格式映射数组 return 键

Map array return key in a string format in JavaScript

我有一个函数可以根据给定数组映射和创建新数组。在我将数组映射到 key: "value" 之后,但是映射函数 return 我 "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" }]

在 JavaScript 对象中,所有键都是字符串。所以下面就是 same/identical:

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

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

当您 运行 下面的代码时,您会看到 即使您的原始输入 在打印时也具有 "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>