What is the best way to convert:
["Foo", "Bar", "John"]
To:
{
Foo: { name: 'Foo', index: 0, type: 'String' },
Bar: { name: 'Bar', index: 1, type: 'String' },
John: { name: 'John', index: 2, type: 'String' },
}
I believe I need to utilize
array.map()
but am not sure how to structure my mapping function. Any insight would be helpful.
You can the function Array.prototype.reduce as follow.
const source = ["Foo", "Bar", "John"],
capitalize = string => string.charAt(0).toUpperCase() + string.slice(1),
result = source.reduce((a, name, index) => ({...a, [name]: {name, index, type: capitalize(typeof name)}}), {});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
your json is not valid , so if you need the valid json like this
[{"name":"Foo","index":0,"type":"string"},{"name":"Foo","index":1,"type":"string"},{"name":"Foo","index":2,"type":"string"}]
you can use this code
var result=[];
arr.forEach( (element,i )=> {
result.push( {name:element, index:i, type: typeof element});
});
UPDATE
for your another json
var jarr=["Foo", "Bar", "John"]
you can use this code
var result = {};
jarr.forEach((element, i) => {
result[element] = { name: element, index: i, type: typeof element };
});
result
{
"Foo": {
"name": "Foo",
"index": 0,
"type": "string"
},
"Bar": {
"name": "Bar",
"index": 1,
"type": "string"
},
"John": {
"name": "John",
"index": 2,
"type": "string"
}
}
I think you could do as follows
const array = ["Foo", "Bar", "John"];
Object.fromEntries(
array
.map((el, index) => {
return [el, {name: el, index, type: el.constructor.name}]
})
)
Here you can find an example snippet:
const array = ["Foo", "Bar", "John"];
const result = Object.fromEntries(
array
.map((el, index) => {
return [el, {name: el, index, type: el.constructor.name}]
})
);
console.log(result);