如何从javascript中获取的数据中的另一个数组替换整个数组

时间:2019-03-07 10:02:33

标签: javascript

很抱歉,我的头衔听起来像是重复的,但我没有找到我想要的答案。请帮忙!

我试图使用javascript中的 fetch()获得一些json值,但是最终我在另一个数组中获取了一个数组。 Array1(Array2())

这是代码

var data=[];
fetch('js/contalist.php')
 .then(function(response) {
  return response.json();
})
 .then(function(myJson) {
var co = myJson
data.unshift(...co);
return co;
});
console.log(data);

我希望有这样的东西:

(4) [{…}, {…}, {…}, {…}]
0: {name: "ARISTOT", email: "someone@example.domain", first_name: "", last_name: ""}
1: {name: "GUEST", email: "someone@example.domain", first_name: "guest", last_name: ""}
2: {name: "KRBTGT", email: "someone@example.domain", first_name: "", last_name: ""}
3: {name: "JOHN", email: "someone@example.domain", first_name: "john", last_name: 
"doe"}
length: 4

只是一个简单的json数据数组

但是我得到这样的东西:

[]
0: {name: "ARISTOT", email: "someone@example.domain", first_name: "", last_name: ""}
1: {name: "GUEST", email: "someone@example.domain", first_name: "guest", last_name: ""}
2: {name: "KRBTGT", email: "someone@example.domain", first_name: "", last_name: ""}
3: {name: "JOHN", email: "someone@example.domain", first_name: "john", last_name: 
"doe"}
length: 4

我想念什么吗?

1 个答案:

答案 0 :(得分:1)

您需要在co的开头添加co的每个项目,而不是整个data数组。

替换此:

data.unshift(co); // this adds the co array as the first element of data

使用spread syntaxunshift

data.unshift(...co); // this adds each co item at the beginning of data

或以此:

data = [...co, ...data]; // spread co items, then spread data into a new array

但是,最后一种解决方案是复制整个数组。

以下是这两种方法的演示:

const co = [1, 2];
const data = [3, 4, 5];

console.log(...[...co, ...data]); // make a copy (immutable)

data.unshift(...co); // or use unshift (mutates the data array)
console.log(...data);