在json对象中拆分字符串并作为数组返回

xt0899hw  于 2023-11-20  发布在  其他
关注(0)|答案(3)|浏览(136)

我正在处理从一个API发送的数据。为了渲染html元素,我需要遍历这些信息。下面的“subjects”数据有问题,因为它是作为字符串发送的,但我只能将其作为数组处理。
json示例

{
    "employees": [
        {
            "id": 7099,
            "subjects": "English,Biology",
        },
        {
            "id": 7100,
            "subjects": "English,French",
        },
        {
            "id": 7101,
            "subjects": "Maths,Science",
        },
        {
            "id": 7102,
            "subjects": "English,Chemistry",
        },
        {
            "id": 7103,
            "subjects": "English,Biology,Chemistry",
        }
    ]
}

字符串
下面是我目前在vue中的组件代码的简化版本:

<template>    
  <div  v-for="employee in employees" :key="employee.id">
    <div v-for="subject in employee.subjects" :key="subject"> 
      {{ subject }} 
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      employees: []
    }
  },
  mounted() {
    fetch('http://localhost:3000/employees')
      .then(response => response.json())
      .then(response => this.employees = response)
  }
}
</script>


我之前遇到过类似的问题,这里建议我将'employee.subjects'发送到一个函数,该函数将拆分字符串并返回它们以插入到html中。这很好用,但在这种情况下它不起作用,因为我需要在将数据插入到html之前按主题过滤数据。
据我所知,我需要遍历json,收集“subjects”,拆分它们,将其存储到一个新数组中,然后插入到原始的“this. jobs”中。
我做过的最大的努力是在下面:

this.employees.forEach((employee) => {}


我不太确定该怎么做。这似乎是一个很简单的任务,但我尝试似乎没有工作。任何想法将不胜感激。

68de4m5k

68de4m5k1#

你需要做的主要改变是:

this.employees = response.employees.map((e) => ({
  ...e,
  subjects: e.subjects.split(","),
}))

字符串
所以你的代码变成:

<template>
  <p v-for="employee in employees" :key="employee.id">
    <div v-for="subject in employee.subjects" :key="subject">
      {{ subject }}
    </div>
  </p>
</template>

<script>
export default {
  data() {
    return {
      employees: [],
    };
  },
  mounted() {
    fetch("http://localhost:3000/employees")
      .then((response) => response.json()).catch(() => mydata)
      .then(
        (response) =>
          (this.employees = response.employees.map((e) => ({
            ...e,
            subjects: e.subjects.split(","),
          }))),
      );
  },
};

const mydata = {
  employees: [
    {
      id: 7099,
      subjects: "English,Biology",
    },
    {
      id: 7100,
      subjects: "English,French",
    },
    {
      id: 7101,
      subjects: "Maths,Science",
    },
    {
      id: 7102,
      subjects: "English,Chemistry",
    },
    {
      id: 7103,
      subjects: "English,Biology,Chemistry",
    },
  ],
};
</script>


工作演示:https://livecodes.io/?x=id/ftgubbhfx5i

hgtggwj0

hgtggwj02#

如果我理解正确的话,response包含了你所展示的结构,你想在赋值给this.employees时将这些字符串转换为数组?类似这样?:

.then(response => this.employees = {
  employees: response.employees.map(employee => ({
    ...employee,
    subjects: employee.subjects.split(',')
  }))
})

字符串
举例来说:

const response = {
    "employees": [
        {
            "id": 7099,
            "subjects": "English,Biology",
        },
        {
            "id": 7100,
            "subjects": "English,French",
        },
        {
            "id": 7101,
            "subjects": "Maths,Science",
        },
        {
            "id": 7102,
            "subjects": "English,Chemistry",
        },
        {
            "id": 7103,
            "subjects": "English,Biology,Chemistry",
        }
    ]
};

const employees = {
  employees: response.employees.map(employee => ({
    ...employee,
    subjects: employee.subjects.split(',')
  }))
};

console.log(employees);

wlwcrazw

wlwcrazw3#

我想你是想把主题变成一个列表和模板。如果是这样的话,你可以做一些像Map的主题和分裂他们的“,“字符。这将把它们变成一个数组。然后我使用模板通过一个forEach循环来运行它,以将它们显示为HTML。我不建议像示例中那样在生产环境中设置innerHTML。但看起来你正在使用或者类似的东西。
我还通过创建一个集合来删除重复项,以防你想删除它,但可以很容易地删除。通过删除这个:
第一个月

const dumbyData = {
    "employees": [
        {
            "id": 7099,
            "subjects": "English,Biology",
        },
        {
            "id": 7100,
            "subjects": "English,French",
        },
        {
            "id": 7101,
            "subjects": "Maths,Science",
        },
        {
            "id": 7102,
            "subjects": "English,Chemistry",
        },
        {
            "id": 7103,
            "subjects": "English,Biology,Chemistry",
        }
    ]
  }
const template = `<div  v-for="employee in employees" :key="employee.id">
    <div v-for="subject in employee.subjects" :key="subject"> 
      {{ subject }} 
    </div>
  </div>`
  
function mounted() {
    return fetch('http://localhost:3000/employees')
      .then(response => response.json())
      .catch(()=>{return dumbyData})
}
const init = async () => {
  const subjects = await mounted()
  const subjectsAsArray = Array.from(new Set(subjects
    .employees
    .map(({subjects})=>subjects.split(","))
    .flat()
    ));
    
  const newArray = subjectsAsArray
    .map((subject)=>{
    const templatedHtml = template.replace("{{ subject }}",subject)
    document.body.innerHTML += templatedHtml
  })
  
  
  
}
init()

字符串

相关问题