Search code examples
javascriptjavascript-objects

Map array return key in a string format in JavaScript


I have a function that map and create a new array from a given array. After I map the array to have a key: "value", but the map function return me the "key": "value".

How can I 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" }]

Solution

  • 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" }