美好的一天
我正在尝试使用自动完成的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"]
})
答案 0 :(得分:1)
要将myObj
转换为所需的数组,可以使用.flatMap
和Object.values
,如下所示:
const myobj = [{
"name": "samuel",
"surname": "anthony"
},
{
"name": "Harmony",
"surname": "Johnson"
}
];
res = myobj.flatMap(Object.values);
console.log(res);
但是,请注意。 flatMap
并非在所有浏览器中都可用,因此并不具有最佳的浏览器兼容性。
如果无法使用.flatMap
,则可以使用.reduce
和destructing assingment作为替代:
const myobj = [{
"name": "samuel",
"surname": "anthony"
},
{
"name": "Harmony",
"surname": "Johnson"
}
];
res = myobj.reduce((acc, {name, surname}) => [...acc, name, surname], []);
console.log(res);
答案 1 :(得分:1)
使用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)
setup.py::build_deps::run()
Failed to run 'bash ../tools/build_pytorch_libs.sh --use-fbgemm --use-nnpack --use-mkldnn --use-qnnpack caffe2'
答案 2 :(得分:0)
您可以使用push()
传播算子将...
Object.values(obj)转换为所需数组
const myobj = [
{
"name": "samuel",
"surname": "anthony"
},
{
"name": "Harmony",
"surname": "Johnson"
}
]
let arr = []
myobj.forEach(obj=> arr.push(...Object.values(obj)));
console.log(arr);
答案 3 :(得分:0)
您可以使用Array.map() method
一个示例用例可能是:
const oldArr = [
{
"name": "Samuel",
"surname": "anthony"
},
{
"name": "Harmony",
"surname": "Johnson"
}
]
const newArr = oldArr.map(x => x.name) // ['Samuel', 'Harmony']
答案 4 :(得分:0)
展平对象:
const myobj = [{
"name": "samuel",
"surname": "anthony"
},
{
"name": "Harmony",
"surname": "Johnson"
}
];
var flatten=myobj.reduce((arr, v)=> [...arr,...[v.name,v.surname]],[]);
console.log(flatten);