Object数组值转换为单个数组

Object数组值转换为单个数组

本文介绍了将Json Object数组值转换为单个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

美好的一天

我正在尝试使用自动完成的jquery框架..买我的问题是我如何才能从json文件或仅是如下所示的快速键入的json对象中获取我的对象,并将所有Object.values(arry)获取到像下面这样的单个数组.

I am trying to use an autocomplete jquery framework.. buy my problem is how can i get my objects either from a json file or just a quick typed json object like the below and get all the Object.values(arry) to a single array like below..

,并且必须是数组..因为自动完成框架仅适用于数组

and must be an array.. because auto complete frameworks only works with arrays

const myobj = [
    {
      "name": "samuel",
      "surname": "anthony"
    },
    {
      "name": "Harmony",
      "surname": "Johnson"
    }
  ]

  const file = "json/user.json";

  fetch('file')
  .then(res => res.json())
  .then((data) =>{
      let i = 0;
      const val = Object.values(data[i]);
      if(i < data.length){
        i++;
        const all = Object.values(data[i]);
        console.log(all);
      }

      var input = document.getElementById("countries");
      var awesomplete = new Awesomplete(input, {
          minChars: 1,
          maxItems: 5,
          autoFirst: true
      });
      awesomplete.list = val;

      //wanted array of
      //["samuel", "anthon", "school"]
  })

推荐答案

要将 myObj 转换为所需的数组,可以使用 .flatMap Object.values 像这样:

To convert myObj to your desired array you can use .flatMap and Object.values like so:

const myobj = [{
    "name": "samuel",
    "surname": "anthony"
  },
  {
    "name": "Harmony",
    "surname": "Johnson"
  }
];

const res = myobj.flatMap(Object.values);
console.log(res);

但是,请注意. flatMap 并非在所有浏览器中都可用,因此它不具有最佳的浏览器兼容性.

However, do note. flatMap is not available in all browsers and so it doesn't have the best browser compatibility.

如果不能使用 .flatMap ,则可以使用 .reduce 破坏分配:

If you cannot use .flatMap you can use .reduce and destructing assignment as an alternative:

const myobj = [{
    "name": "samuel",
    "surname": "anthony"
  },
  {
    "name": "Harmony",
    "surname": "Johnson"
  }
];

const res = myobj.reduce((acc, {name, surname}) => [...acc, name, surname], []);
console.log(res);

这篇关于将Json Object数组值转换为单个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 03:09