简体   繁体   English

在 JavaScript 中使用三元运算删除字符串

[英]Remove a string using Ternary operation in JavaScript

I have something like this in my console: How can I take out the [object Object] from my output?我的控制台中有这样的内容:如何从我的 output 中取出 [object Object]?

I want the output printed without the [Object Object].我想要在没有 [Object Object] 的情况下打印 output。 Probably using a ternary operation?可能使用三元运算?

data:[object Object]
  text:Data is supplied by Government
  link:https://en.wikipedia.org/

This is my code:这是我的代码:

 const GetData = (obj, step) => { let padSpace = "" for (let j=0; j < step; j++) { padSpace += '' } for (let k in obj) { console.log(padSpace + k + ':' + obj[k]) if (typeof(obj[k]) === "object") { if (Array.isArray(obj[k])) { obj[k].forEach(element => { if (typeof(element === "object")) { GetData(element, step + 1); } else { console.log(padSpace + element) } } ); } else { GetData(obj[k], step + 1); } } else {} }

I want something like:我想要这样的东西:

I am not an expert but I'll try to help here.我不是专家,但我会尽力在这里提供帮助。

This data is coming from an external API, I suppose.我想这个数据来自外部 API。 Right?正确的? It seems to me that is just a matter of how the data is being sent back from the server.在我看来,这只是数据如何从服务器发回的问题。 Maybe you just need to use JSON.stringfy to convert the object to string.也许您只需要使用 JSON.stringfy 将 object 转换为字符串。

It would be nice to have access to the kind of data being sent from the server to manipulate it.如果能够访问从服务器发送的数据类型以对其进行操作,那就太好了。

Hope it starts to help you in a way...希望它开始以某种方式帮助你......

Cheers干杯

The following test will always pass because typeof true and typeof false are both "boolean" which is truthy.下面的测试总是会通过,因为typeof truetypeof false都是"boolean" ,也就是 truthy。

if (typeof(element === "object")) {

Try尝试

if (typeof element === "object") {

I have no idea why you are talking about a ternary operation.我不知道你为什么要谈论三元运算。


To avoid the [object Object] you can move the existing console.log and add another one as shown:为避免[object Object] ,您可以移动现有的console.log并添加另一个,如下所示:

for (let prop in entity) {  
  if (typeof entity[prop] === "object") {
    console.log(padString + prop + ':');
    if (Array.isArray(entity[prop])) {
      entity[prop].forEach(element => {
        if (typeof element === "object") {
          formatData(element, level + 1);
        } else {
          console.log(padString + element)
        }
      });
    } else {
      formatData(entity[prop], level + 1);
    }
  } else {
    console.log(padString + prop + ':' + entity[prop])
  }
}

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

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