将对象数组转换为键数组数组

时间:2018-03-01 14:54:53

标签: javascript arrays

我有一个JSON输入格式,这是一个例子:

{
  "friends": [
    {
      "id": "5a8d4euyiuyiuyhiuyc022c7158d5",
      "name": "Gloria Coffey"
    },
    {
      "id": "5a8d4e2rytuyiyuyiytiy3e426",
      "name": "Shawn Ellison"
    }
  ]
}

我会将它转换为数组键:值数组,如下所示:

[[id : "5a8d4euyiuyiuyhiuyc022c7158d5", name:"Gloria Coffey"],[id : "5a8d4e2rytuyiyuyiytiy3e426", name:"Shawn Ellison"]]

我做了什么:

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);
});

this.results的第一个console.log打印出一个对象数组

然后我的output数组打印:

0:Array(2)
0:"0" <-- ??
1:{
   id:"5a8d4e2ffead0c022c7158d5",
   name:"Gloria Coffey"
}length:2__proto__:Array(0)

我想要的是什么

id : 5a8d4e2ffead0c022c7158d5
name : Gloria Coffey

2 个答案:

答案 0 :(得分:0)

你想要实现的目标是不可能的。你想要的最接近的解决方案是这样的:

&#13;
&#13;
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))
&#13;
&#13;
&#13;

这不是数组,但您可以像以下一样访问它:

let myObj = convert(friends)
console.log(myObj['5a8d4euyiuyiuyhiuyc022c7158d5'])

我希望这会做你想做的事。

答案 1 :(得分:0)

您也可以使用Object.fromEntries()来做到这一点:

function flattenArrayToObject(arr) {
  let entries = arr.map(el => [el.id, el.name])
  let obj = Object.fromEntries(entries)
  return obj;
}

或者,如果您确实需要:

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))