无法控制JSON数组中的唯一名称

wwtsj6pe  于 2023-01-10  发布在  其他
关注(0)|答案(2)|浏览(112)

我有一个包含数百个对象的JSON数组,其中每个JSON对象都有namehobbies属性。
下面是JSON结构:

const data = [
 {
  name:'Paul',
  hobbies: ['Football','Reading']
 },
 {
  name:'Riya',
  hobbies: ['Singing','Dancing']
 },
 {
  name:'Jack',
  hobbies: ['Gaming']
 }
]

这里,如果我迭代这些数据,它将多次给予相同的名称,无论是否存在多个爱好。因此,如果我是console,结果将是

Paul,Football
Paul,Reading
Riya,Singing
Riya,Dancing
Jack,Gaming

我不希望以上输出,我希望无论哪里有相同的名称是在同一个对象来不要控制台它像下面:

Paul,Football
"",Reading
Riya,Singing
"",Dancing
Jack,Gaming

下面是我的代码:

const data = [
  {
   name:'Paul',
   hobbies: ['Football','Reading']
  },
  {
   name:'Riya',
   hobbies: ['Singing','Dancing']
  },
  {
   name:'Jack',
   hobbies: ['Gaming']
  }
 ]

const example = (data) => {

for(var i=0;i<data.length;i++){

    for(var j=0;j<data[i].hobbies.length;j++){

        console.log(data[i].name,data[i].hobbies[j]);

         if(i=0){
           console.log(data[i].name,data[i].reports[j]);
        }
        else{
            const prev = i-1;
            if(data[prev].name == data[i].name) { //Getting TypeError here cannot read property 'name' of undefined 
               console.log("",data[i].reports[j]);
            }
            else{
               console.log(data[i].name,data[i].reports[j]); 
            }
        }
      }
    }
 }

example(data);

在上面的代码中,我试图比较数据数组中名称的前一个值与名称的当前值,如果相同,则使名称字段为" ",否则将名称值放入,对于位置0的第一个元素,我将按原样放入值。
有人让我知道为什么我得到这个TypeError。任何帮助表示感谢。

gjmwrych

gjmwrych1#

有几个问题,首先是错字,你分配而不是比较

if (i=0) {
// ^^^^^
  console.log(data[i].name,data[i].reports[j]);
}

剩下的就是逻辑了,您所要做的就是检查j的索引

const example = data => {
  for (var i = 0; i < data.length; i++) {
    for (var j = 0; j < data[i].hobbies.length; j++) {
      if (j == 0) {
        console.log(data[i].name, data[i].hobbies[j])
      } else {
        console.log("", data[i].hobbies[j])
      }
    }
  }
}

完整解决方案

const data = [
  {
    name: "Paul",
    hobbies: ["Football", "Reading"],
  },
  {
    name: "Riya",
    hobbies: ["Singing", "Dancing"],
  },
  {
    name: "Jack",
    hobbies: ["Gaming"],
  },
]

const example = data => {
  for (var i = 0; i < data.length; i++) {
    for (var j = 0; j < data[i].hobbies.length; j++) {
      if (j == 0) {
        console.log(data[i].name, data[i].hobbies[j])
      } else {
        console.log("", data[i].hobbies[j])
      }
    }
  }
}

example(data)
1tuwyuhd

1tuwyuhd2#

const data = [
 {
  name:'Paul',
  hobbies: ['Football','Reading']
 },
 {
  name:'Riya',
  hobbies: ['Singing','Dancing']
 },
 {
  name:'Jack',
  hobbies: ['Gaming']
 }
]

data.forEach(d => {
  d.hobbies.forEach((hobby, index) => {
    const name = index == 0 ? d.name : '""'
    console.log(name + ',' + hobby)
  })
})

如果爱好索引为0,则只打印名称

相关问题