简体   繁体   English

Typescript 模块导入对象文字

[英]Typescript Module Import Object Literals

Edit: My first iteration of this question was too simplified, resulting in simply allowing me to import the entire object, but not to access any of the properties.编辑:我对这个问题的第一次迭代过于简化,导致我只允许导入整个对象,但不能访问任何属性。 I've updated this to demonstrate my issue more precisely.我已经更新了这个以更准确地展示我的问题。 I've also added the actual async/awaits I will use in the actual program.我还添加了我将在实际程序中使用的实际异步/等待。

I've also introduced errors in the json to simulate the error-prone data I'm using, and a try/catch block to skip over error iterations, though this shouldn't change the functionality I'm expecting.我还在 json 中引入了错误来模拟我正在使用的容易出错的数据,以及一个 try/catch 块来跳过错误迭代,尽管这不应该改变我所期望的功能。

I want to import JSON data into one typescript module, do some operations, return an object literal with results, and then import that object literal into another file to do further operations, and refer to it using dot notation, however I can only access the object after import - every attempt to access properties ends with 'undefined'我想将 JSON 数据导入一个打字稿模块,执行一些操作,返回一个带有结果的对象文字,然后将该对象文字导入另一个文件以进行进一步的操作,并使用点表示法引用它,但是我只能访问导入后的对象 - 每次访问属性的尝试都以“未定义”结尾

I have simplified the operations as much as possible to isolate the problem, but can't find it:我已经尽可能简化了操作以隔离问题,但找不到:

JSON data: JSON数据:

{
    "THINGS":[
        {
            "name":"thing1",
            "color":"blue"
        },
        {
            "name":"thing2",
            "color":"red"
        },
        {
            "name":"thing3",
            "color":"orange"
        },
        {
            "name":"thing4",
            "color":"purple"
        },
        {
            "error": "error",
            "error2": "error"
        }
    ]
}

test import JSON:测试导入 JSON:

import rawdata from './rawdata.json' assert { type: "json" };

export async function test(){
    const data = rawdata.THINGS.map(async(Data)=>{
        let name = Data.name;
        let color = Data.color;
        let obj = {
            "name": name,
            "color": color
        }
        return obj
    });
    return(data)
};

// pass it to another function and do some stuff to it:

async function testImport(){
    let d = await test();
    let q = d.map((e) => {
        let p = (d.name + " wuz here")
        return p
    });
    console.log(q)
}
testImport();

/*
returns:
[
  'undefined wuz here',
  'undefined wuz here',
  'undefined wuz here',
  'undefined wuz here',
  'undefined wuz here'
]
*/

I can't believe I'm having so much trouble with such a simple procedure, so I have to ask on StackOverflow because I've obviously missed some crucial fundamental of modules and objects.我不敢相信我在这么简单的过程中遇到了这么多麻烦,所以我不得不在 StackOverflow 上提问,因为我显然错过了模块和对象的一些关键基础知识。

This line:这一行:

const data = rawdata.THINGS.map(async (Data) => {

Creates an array of promise objects.创建一个 Promise 对象数组。 To resolve all the promises in that array you need to use:要解决该数组中的所有承诺,您需要使用:

return Promise.all(data)

Now the function returns a single promise that resolves to an array of objects, instead of an array of promises that each resolve to a single object.现在,该函数返回一个解析为对象数组的单个 Promise,而不是每个解析为单个对象的 Promise 数组。


The second problem is here:第二个问题在这里:

    let d = await test();
    let q = d.map((e) => {
        let p = (d.name + " wuz here")
        return p
    });

in the map callback you access d.name but d is the array, not the item.map回调中,您访问d.named是数组,而不是项目。 You chose to assign each item to e but do not use that variable in your function.您选择将每个项目分配给e但不在函数中使用该变量。 If you change that to e.name it works as you expect:如果将其更改为e.name ,它将按预期工作:

["thing1 wuz here", "thing2 wuz here", "thing3 wuz here", "thing4 wuz here"]

This is why, even for contrived example code single letter variable names are frowned upon.这就是为什么,即使对于人为的示例代码,单字母变量名也不受欢迎。

If your code was instead this:如果您的代码是这样的:

let items = await test()
let mappedItems = items.map(item => {
  let description = items.name + " wuz here"
})

Then it would be far easier to tell that items.name is accessing the name property on the array, which doesn't make very much sense.然后更容易告诉items.name正在访问数组上的name属性,这没有多大意义。

See working example here .请参阅此处的工作示例。 Just expand the "console" on the bottom right and you'll see the correct output.只需展开右下角的“控制台”,您就会看到正确的输出。


Original Answer原始答案

This line:这一行:

const data = rawdata.THINGS.forEach((Data)=>{

Will always leave data as undefined .将始终将data保留为undefined This is because array.forEach() returns undefined .这是因为array.forEach()返回undefined So I'm not sure why you think that's return values.所以我不确定你为什么认为这是返回值。

You probably want to use array.map() which returns a new array filled with the returned values.您可能想要使用array.map()返回一个填充了返回值的新数组。

export function test() {
  const data = rawdata.THINGS.map((Data) => {
    let name = Data.name;
    let color = Data.color;
    let info = {
      name: name,
      color: color
    };
    return info;
  });
  return data;
}

See this codesandbox for a working example:有关工作示例,请参阅此代码框

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM