首页 > 解决方案 > 使用项目计数创建新对象

问题描述

我想创建一个从少数来源获取参数的函数,并返回一个带有新对象的承诺。所以,我有一个包含所有数据的基础对象,还有另一个函数,它接受一个参数并进行一些操作并返回另一个数据。主要问题是我有一些竞争条件或新对象没有按需要更改,可能是因为嵌套函数。

我试图查看其他答案,但没有成功。

足够的介绍,这是我的一些代码:

imports...

const createNewObject = async () => {
    try {
        const baseObjFromRequest = await myClient.request(query); // Returns array of objects


        // this is the base object structure that returns from request:
        baseObjFromRequest = [
            {data: "some data x", val: 1},
            {data: "some data y", val: 8},
            {data: "some data z", val: 7},
            {data: "some data x", val: 3},
            {data: "some data z", val: 11},
        ]

        // the pipeline should iterate over the array, with the converter function
        // and return the info as the key of the new object
        // which key is a counter of the values

          newObject = {}

          baseObjFromRequestAbove.forEach(item => {
            let keyFromConverter = converter(item.data);
            newObject[keyFromConverter] += item.val;
          })

        // Now I want to return new object (as promise)
        // in this structure, but somehow it breaks any time and not return it as well.

        newObject = {
            info_from_x: 4, // The value is the count of 
            info_from_y: 8,
            info_from_z: 18,
        }

        return newObject; // As promise
         
    } catch (error) {
        console.error(err);
    }
}

//  This function do a call and convert the data to new info data
const converter = async (data) => {
    let query = { "info": data }
    try {
        const resp = await axios.post(URL + '/info', query);
        const data = await resp.data;
        return data;
    } catch (err) {
        console.error(err);
    }
};

标签: javascriptarraysobjectreduce

解决方案


推荐阅读