I have some data I'd like to display in my front end but its name property is an array of objects, with an object nested in that object. This is how the data is structured in the request:
name: Array [ {…} ]
0: Object { 0: "E", 1: "r", 2: "i", … }
0: "E"
1: "r"
2: "i"
3: "c"
4: " "
5: "C"
6: " "
7: "P"
8: "e"
9: "z"
10: "z"
11: "u"
12: "l"
13: "o"
_id: "6186b6777a38b7da536a6ffd"
<prototype>: Object { … }
length: 1
I can't map through it (userData.name[0].map
) because its not an array.
Whats the correct way to iterate though an object like this and join each letter together?
CodePudding user response:
As of right now I'm using this
const fullName = Object.values(userData.name[0]);
console.log(fullName);
fullName.pop();
const name = fullName.join("");
console.log(name);
Which gives me what I'm looking for (// Eric C Pezzulo
)
Its not pretty but it works, If anyone has a simpler way to do this or clean this up I'm open to any suggestions.
CodePudding user response:
Something like this may look a little cleaner
const arr = [
{
0: 'E',
1: 'r',
2: 'i',
3: 'c',
4: ' ',
5: 'C',
6: ' ',
7: 'P',
8: 'e',
9: 'z',
10: 'z',
11: 'u',
12: 'l',
13: 'o',
_id: '6186b6777a38b7da536a6ffd'
}
];
const fullName = Object.values(arr[0]).slice(0, -1).join('');
console.log(fullName);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
CodePudding user response:
I don't know that there's a simpler way, but if you use slice you can do it all in one chained line. You could also create a function, for readability and extension.
const arr = [{
0: 'E', 1: 'r', 2: 'i', 3: 'c', 4: ' ', 5: 'C', 6: ' ',
7: 'P', 8: 'e', 9: 'z', 10: 'z', 11: 'u', 12: 'l', 13: 'o',
_id: '6186b6777a38b7da536a6ffd'
}];
let name = Object.values(arr[0]).slice(0,-1).join('');
console.log(name);
const getFull=(o)=>Object.values(o).slice(0,-1).join('');
console.log(getFull(arr[0]));
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Or to transform all:
const arr = [{
0: 'E', 1: 'r', 2: 'i', 3: 'c', 4: ' ', 5: 'C', 6: ' ',
7: 'P', 8: 'e', 9: 'z', 10: 'z', 11: 'u', 12: 'l', 13: 'o',
_id: '6186b6777a38b7da536a6ffd'
},{
0: 'C', 1: 'h', 2: 'r', 3: 'i', 4: 's', 5: ' ',
7: 'S', 8: 't', 9: 'r', 10: 'i', 11: 'c', 12: 'k', 13: 'l', 14: 'a', 15: 'n', 16: 'd',
_id: '6186b6777a38b7da536a6ffd'
}];
const getFull=(o)=>Object.values(o).slice(0,-1).join('');
let buffer = arr.map(a=>getFull(a));
console.log(buffer);
<iframe name="sif3" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>