Home > Back-end >  Map array return key in a string format in js
Map array return key in a string format in js

Time:12-13

I have a function than map and create a new array from given array. After i've map the array to have a key: "value", but the map function return me the "key": "value". How i can get or map the key not in a string format ?

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);

the result is this

["f34f43","233edd3"]

now i want to add a key (name) for each value and convert in a object

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

this is the result :

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

but i need like that, with key not like a string.

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

CodePudding user response:

In a JavaScript object, all keys are strings. So the followings are exactly the same/identical:

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

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

CodePudding user response:

When you run the code below, you will see that even your original input has object properties in the form "key": "value" when printed:

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, what you get if you used JSON.stringify.

If you really really need the string representation to look like ES5 syntax, see my answer to the above linked SO question. Per that answer, below I use JSON5.stringify from the JSON5 library, which has a compatible interface to the built-in JSON object:

// 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>

  • Related