How do I convert a string array:
var names = [
"Bob",
"Michael",
"Lanny"
];
into an object like this?
var names = [
{name:"Bob"},
{name:"Michael"},
{name:"Lanny"}
];
Array. filter() removes all duplicate objects by checking if the previously mapped id-array includes the current id ( {id} destructs the object into only its id). To only filter out actual duplicates, it is using Array.
To duplicate an array, just return the element in your map call. numbers = [1, 2, 3]; numbersCopy = numbers. map((x) => x); If you'd like to be a bit more mathematical, (x) => x is called identity.
Duplicate elements can be found using two loops. The outer loop will iterate through the array from 0 to length of the array. The outer loop will select an element. The inner loop will be used to compare the selected element with the rest of the elements of the array.
If the lengths are not the same, it must follow that the array contained duplicate values! If the length of the Set and the array are not the same this function will return true , indicating that the array did contain duplicates.
Super simple Array.prototype.map()
job
names.map(name => ({ name }))
That is... map each entry (name
) to an object with key "name" and value name
.
var names = [
"Bob",
"Michael",
"Lanny"
];
console.info(names.map(name => ({ name })))
Silly me, I forgot the most important part
names.map(name => name === 'Bob' ? 'Saab' : name)
.map(name => ({ name }))
You can do this too:
var names = [
"Bob",
"Michael",
"Lanny"
];
var objNames = []
names.forEach(name => {
objNames.push({
name
})
})
Using ES6 you can set name
and it is equal to name: name
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With