gpt4 book ai didi

javascript - 将 Json 对象数组值转换为单个数组

转载 作者:行者123 更新时间:2023-12-01 01:18:36 24 4
gpt4 key购买 nike

美好的一天

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

["samue", "anthon", "Harmony", "Johnson"]

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

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"]
})

最佳答案

使用减少

const myobj = [
{
"name": "samuel",
"surname": "anthony"
},
{
"name": "Harmony",
"surname": "Johnson"
}
]
console.log(myobj.reduce((acc,e)=>{acc.push(e.name);acc.push(e.surname);return acc},[]))

使用forEach

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

var a=[];
myobj.forEach((e)=>{a.push(e.name);a.push(e.surname)})
console.log(a)

关于javascript - 将 Json 对象数组值转换为单个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54476513/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com