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.
CodePudding user response:
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; }
CodePudding user response:
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
i=0;
var newObj=[];
arr.forEach(element => {
newObj.push( {name:element, index:i, type: typeof element});
i ;
});
UPDATE
for this
var jarr=["Foo", "Bar", "John"]
you can use this
i=0;
var newObj={};
jarr.forEach(element => {
newObj[element]={name:element, index:i, type: typeof element};
i
});
result
{
"Foo": {
"name": "Foo",
"index": 0,
"type": "string"
},
"Bar": {
"name": "Bar",
"index": 1,
"type": "string"
},
"John": {
"name": "John",
"index": 2,
"type": "string"
}
}
CodePudding user response:
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);