I Have a JSON input format, here's an exemple :
{
"friends": [
{
"id": "5a8d4euyiuyiuyhiuyc022c7158d5",
"name": "Gloria Coffey"
},
{
"id": "5a8d4e2rytuyiyuyiytiy3e426",
"name": "Shawn Ellison"
}
]
}
I would transform it to an array key: value arrays, something like this :
[[id : "5a8d4euyiuyiuyhiuyc022c7158d5", name:"Gloria Coffey"],[id : "5a8d4e2rytuyiyuyiytiy3e426", name:"Shawn Ellison"]]
What I have done :
search(event) {
this.searchRmpmService.getResults(event.query).then(data => {
this.results = data.friends;
console.log(this.results);
let output = [];
output= Object.entries(this.results);
console.log(output);
});
the first console.log of this.results
prints me an array of objects
then my output
array prints:
0:Array(2)
0:"0" <-- ??
1:{
id:"5a8d4e2ffead0c022c7158d5",
name:"Gloria Coffey"
}length:2__proto__:Array(0)
what I would is
id : 5a8d4e2ffead0c022c7158d5
name : Gloria Coffey
What you are trying to achieve is not possible. The nearest solution of what you want to would be something like this:
let friends = [ { id: "5a8d4euyiuyiuyhiuyc022c7158d5", name: "Gloria Coffey" }, { id: "5a8d4e2rytuyiyuyiytiy3e426", name: "Shawn Ellison" } ] function convert(param) { let res = {} for (let item of param) { let id = item.id res[id] = item.name } return res } console.log(convert(friends))
This is not an array, but you can access it like:
let myObj = convert(friends)
console.log(myObj['5a8d4euyiuyiuyhiuyc022c7158d5'])
I hope this will do what you want.
You could also do it by using Object.fromEntries()
like this:
function flattenArrayToObject(arr) {
let entries = arr.map(el => [el.id, el.name])
let obj = Object.fromEntries(entries)
return obj;
}
Or in a one liner if you really needed to:
let flattenArray = arr => Object.fromEntries(arr.map(el => [el.id, el.name]))
let friends = [ {id: "158d5", name: "Gloria"}, {id: "3e426", name: "Shawn"} ] function flattenArrayToObject(arr) { let entries = arr.map(el => [el.id, el.name]) // [["158d5","Gloria"], ["3e426","Shawn"]] let obj = Object.fromEntries(entries) return obj; } console.log(flattenArrayToObject(friends))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.