【问题标题】:how to merge 2 arrays in angular 7 typescript如何在 Angular 7 打字稿中合并 2 个数组
【发布时间】:2019-05-12 06:47:01
【问题描述】:

在特定组件的 Angular 7 项目中,我必须通过 api 从 wp 站点和 dotnet 站点获取数据。 从 wp api 我得到的数据是(控制台日志数据):

(2) [{…}, {…}]
0: {title: "Henk WJ Ovink", description: "Special Envoy for International Water Affairs, Kin…ands, and Sherpa to the High Level Panel on Water", slug: "http://siwidev.websearchpro.net/press/", image: "http://siwidev.websearchpro.net/wp-content/uploads/2019/03/636385501414087698.png", imageWidth: 1903, …}
1: {title: "Amina J. Mohammed", description: "Deputy Secretary-General United Nations", slug: "http://siwidev.websearchpro.net/community/", image: "http://siwidev.websearchpro.net/wp-content/uploads/2019/03/h20fddcc.jpg", imageWidth: 776, …}
length: 2
__proto__: Array(0)

我从 dotnet api 获取数据(控制台日志数据):

(5) [{…}, {…}, {…}, {…}, {…}]
0: {id: 8342, title: "Panaceas or painkillers – what role for sustainability assessment tools?", description: null, slug: "8342-panaceas-or-painkillers---what-role-for-sustainability-assessment-tools", image: "https://siwi.websearchpro.net/Content/ProposalReso…g-2019-8342-tn-img-2019-8605-iStock-500553193.jpg", …}
1: {id: 8380, title: "Inclusive Policy and Governance for Water and Sanitation ", description: null, slug: "8380-inclusive-policy-and-governance-for-water-and-sanitation", image: "https://siwi.websearchpro.net/Content/ProposalReso…019-8420-img-2019-8420-org-InkedPhoto IWRM_LI.jpg", …}
2: {id: 8464, title: "Cities4Forests: 50 cities commit to forests citing water benefits", description: null, slug: "8464-cities4forests-50-cities-commit-to-forests-citing-water-benefits", image: "https://siwi.websearchpro.net/Content/ProposalReso…464-tn-img-2019-8481-WESCA illegal FS dumping.jpg", …}
3: {id: 8474, title: "Urban water resiliency: a coordinated response from source to settlement ", description: null, slug: "8474-urban-water-resiliency-a-coordinated-response-from-source-to-settlement", image: "https://siwi.websearchpro.net/Content/ProposalResources/Image/Default/default-www-tn.jpg", …}
4: {id: 8526, title: "Including all: participatory approaches in water governance and programmes ", description: null, slug: "8526-including-all-participatory-approaches-in-water-governance-and-programmes", image: "https://siwi.websearchpro.net/Content/ProposalReso…ge/2019/Thumbnail/img-2019-8526-tn-Field trip.JPG", …}
length: 5
__proto__: Array(0)

现在我需要合并这两个数组,打乱数组元素并显示它。 到目前为止我做了什么:

public merge_array : Array<{ }> = [];
/* wp api */
this.accountService.getKeynote( wp_params ).then( ( response: any ) => {
    this.merge_array ? this.merge_array : [];
    this.wp_data_array = response.data;
    for ( let value of this.wp_data_array ) {
        this.merge_array.push( value );
    };
});
/* dot net api */
this.accountService.getConferences( params ).then( ( dotnetresponse: any ) => {
    if ( dotnetresponse.status == 'Ok' ) {
        this.merge_array ? this.merge_array : [];
        this.dotnet_data_array = dotnetresponse.conferences;
        for ( let value of this.dotnet_data_array ) {
            this.merge_array.push( value );
        };
    }
});

但是当我在这里控制台登录“merge_array”时,结果是:

[]
0: {title: "Henk WJ Ovink", description: "Special Envoy for International Water Affairs, Kin…ands, and Sherpa to the High Level Panel on Water", slug: "http://siwidev.websearchpro.net/press/", image: "http://siwidev.websearchpro.net/wp-content/uploads/2019/03/636385501414087698.png", imageWidth: 1903, …}
1: {title: "Amina J. Mohammed", description: "Deputy Secretary-General United Nations", slug: "http://siwidev.websearchpro.net/community/", image: "http://siwidev.websearchpro.net/wp-content/uploads/2019/03/h20fddcc.jpg", imageWidth: 776, …}
2: {id: 8342, title: "Panaceas or painkillers – what role for sustainability assessment tools?", description: null, slug: "8342-panaceas-or-painkillers---what-role-for-sustainability-assessment-tools", image: "https://siwi.websearchpro.net/Content/ProposalReso…g-2019-8342-tn-img-2019-8605-iStock-500553193.jpg", …}
3: {id: 8380, title: "Inclusive Policy and Governance for Water and Sanitation ", description: null, slug: "8380-inclusive-policy-and-governance-for-water-and-sanitation", image: "https://siwi.websearchpro.net/Content/ProposalReso…019-8420-img-2019-8420-org-InkedPhoto IWRM_LI.jpg", …}
4: {id: 8464, title: "Cities4Forests: 50 cities commit to forests citing water benefits", description: null, slug: "8464-cities4forests-50-cities-commit-to-forests-citing-water-benefits", image: "https://siwi.websearchpro.net/Content/ProposalReso…464-tn-img-2019-8481-WESCA illegal FS dumping.jpg", …}
5: {id: 8474, title: "Urban water resiliency: a coordinated response from source to settlement ", description: null, slug: "8474-urban-water-resiliency-a-coordinated-response-from-source-to-settlement", image: "https://siwi.websearchpro.net/Content/ProposalResources/Image/Default/default-www-tn.jpg", …}
6: {id: 8526, title: "Including all: participatory approaches in water governance and programmes ", description: null, slug: "8526-including-all-participatory-approaches-in-water-governance-and-programmes", image: "https://siwi.websearchpro.net/Content/ProposalReso…ge/2019/Thumbnail/img-2019-8526-tn-Field trip.JPG", …}
length: 7
__proto__: Array(0)

合并数组的长度为 0。我无法解决这个问题。关于数组初始化或数组推送,我做错了什么。 欢迎任何帮助/建议。

【问题讨论】:

  • length: 7 - 为什么断定它为零? Array(0)原型
  • @jonrsharpe 我做了 console.log(this.merge_array.length) 并且它给了我 0 认为有数据。我需要数组长度,但无论如何我总是得到 0?
  • 你是吗?因为在您发布的输出中,我们可以看到它是 7。
  • @jonrsharpe 是的,它确实显示,但是当我控制台长度(console.log(this.merge_array.length))它总是显示 0。除了 0,我似乎无法得到确切的长度。

标签: arrays angular typescript angular7 array-push


【解决方案1】:

数组为空并不奇怪,因为 Promises 的返回是异步操作的。因此,当您记录值时,两个数组都将为空。

您需要做的是使用Promise.all。根据文档,

Promise.all() 方法返回一个 Promise,当所有作为可迭代对象传递的承诺都已解决或可迭代对象不包含任何承诺时,该 Promise 将解决。它以第一个拒绝的承诺的原因拒绝。

现在可以做的是使用 Promise.all 来解决来自两个请求的承诺(您可以使用 console.log(response) 来验证承诺确实已解决并返回一个值),然后使用 spread syntax合并两个数组。然后我们将使用 Laurens Holst 在here 上提供的算法随机重新排列数组。这应该会给你结果洗牌的数组。

const getKeynote = this.accountService.getKeynote(wp_params);
const getConferences = this.accountService.getConferences(params);

Promise.all([getKeynote, getConferences]).then(response => {
  //console.log(response);
  const merged = [...response[0], ...response[1]];
  const shuffleArray = (array) => {
    for (let i = array.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [array[i], array[j]] = [array[j], array[i]];
    }
  };
  shuffleArray(merged);
  console.log(merged);
});

【讨论】:

    【解决方案2】:

    简单的Object.assign(target, source) 应该可以解决问题

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign的文档

    要打乱数组,请使用解构

    for (let i = target.length - 1; i > 0; i--) {
        const j = Math.floor(Math.random() * (i + 1));
        [target[i], target[j]] = [target[j], target[i]];
    }
    

    【讨论】:

    • 它让我得到一个空数组。
    猜你喜欢
    • 2021-02-27
    • 2019-06-06
    • 2019-06-06
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    • 2019-12-24
    • 1970-01-01
    • 2016-10-31
    相关资源
    最近更新 更多