如何在 angular 7 打字稿中合并 2 个数组

how to merge 2 arrays in angular 7 typescript

在特定组件的 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。我无法解决这个问题。关于数组初始化或数组推送,我做错了什么。 欢迎任何help/suggestions。

简单 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]];
}

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

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

The Promise.all() method returns a single Promise that resolves when all of the promises passed as an iterable have resolved or when the iterable contains no promises. It rejects with the reason of the first promise that rejects.

现在可以做的,是使用Promise.all来解决两个请求的承诺(您可以使用console.log(response)来验证承诺确实得到解决并返回一个值),然后通过使用 Laurens Holst 的 spread syntax to merge both arrays. Then we will randomly reshuffle the array using the algorithm provided over 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);
});