【问题标题】:How to loop through json obejct and return keys and values if they are all different or even null? Vue, Javascript如果它们都不同甚至为null,如何循环遍历json对象并返回键和值?值,Javascript
【发布时间】:2021-09-23 11:03:12
【问题描述】:

需要通过一个 JSON 对象,该对象可能有也可能没有属性字段,它可以为空,也可以有 10 个不同的字段,然后我需要在代码块中打印它,JSON 数据在这里:

 "grade": [
        {
            "alias": "G1",
            "id": "4d72868e-c46f-41d1-83a6-429a2421fd34",
            "name": "Grade 1",
            "properties": {
                "size": "A1",
                "dimensions": "2x2",
                "maturity_weight": "150"
            },
            "createdAt": "2020-03-30T09:57:24.756Z",
            "updatedAt": "2020-03-30T09:57:24.756Z",
            "farmId": "703ab269-20f5-4dca-8687-e14de5f6a4cb"
        },
        {
            "alias": "G2",
            "id": "62fbefef-3342-43aa-8ed3-ed2ff0ff7cd6",
            "name": "Grade 2",
            "properties": {
                "size": "A2",
                "dimensions": "3x3",
                "maturity_weight": "150"
            },
            "createdAt": "2020-11-22T13:29:42.461Z",
            "updatedAt": "2020-11-22T13:29:42.461Z",
            "farmId": "703ab269-20f5-4dca-8687-e14de5f6a4cb"
        },
        {
            "alias": "G3",
            "id": "9ce20ee1-c197-4775-97cb-35998ce51d4b",
            "name": "Grade 3",
            "properties": {
                "size": "A3",
                "dimensions": "4x4",
                "maturity_weight": "150"
            },
            "createdAt": "2020-11-22T13:31:16.955Z",
            "updatedAt": "2020-11-22T13:31:16.955Z",
            "farmId": "703ab269-20f5-4dca-8687-e14de5f6a4cb"
        },
        {
            "alias": "G4",
            "id": "83f6ff4b-ab75-4930-ab84-59763b24d435",
            "name": "Grade 4",
            "properties": {
                "size": "A4",
                "dimensions": "4x4",
                "maturity_weight": "150"
            },
            "createdAt": "2020-11-22T13:31:16.955Z",
            "updatedAt": "2020-11-22T13:31:16.955Z",
            "farmId": "703ab269-20f5-4dca-8687-e14de5f6a4cb"
        },
        {
            "alias": "G5",
            "id": "8dea25be-93e3-4ab4-ae58-685e4ab05dbf",
            "name": "Grade 5",
            "properties": {
                "units": "gms",
                "maxWeight": "170",
                "minWeight": "100"
            },
            "createdAt": "2020-08-11T08:52:23.484Z",
            "updatedAt": "2020-08-11T08:52:23.484Z",
            "farmId": "703ab269-20f5-4dca-8687-e14de5f6a4cb"
        },
        {
            "alias": "G6",
            "id": "85aa81e4-b428-44d5-9ee2-4215de6c8226",
            "name": "Grade 6",
            "properties": null,
            "createdAt": "2020-05-15T09:53:23.809Z",
            "updatedAt": "2020-05-15T09:53:23.809Z",
            "farmId": "703ab269-20f5-4dca-8687-e14de5f6a4cb"
        },
        {
            "alias": "SG",
            "id": "f4cd4ec4-1b99-42b1-839b-cd18c54d1761",
            "name": "some grade",
            "properties": {
                "shape": "",
                "units": "gms",
                "dimension": "",
                "maxWeight": "2",
                "minWeight": "1"
            },
            "createdAt": "2021-06-11T15:10:39.102Z",
            "updatedAt": "2021-06-11T15:10:39.102Z",
            "farmId": "703ab269-20f5-4dca-8687-e14de5f6a4cb"
        },
        {
            "alias": "SO",
            "id": "ef862161-e3e9-4b84-9164-178a600a15a8",
            "name": "som",
            "properties": {
                "shape": null,
                "units": "gms",
                "dimension": null,
                "maxWeight": "3",
                "minWeight": "2"
            },
            "createdAt": "2021-06-11T15:18:16.460Z",
            "updatedAt": "2021-06-11T15:18:16.460Z",
            "farmId": "703ab269-20f5-4dca-8687-e14de5f6a4cb"
        },
        {
            "alias": "AS",
            "id": "4a4e1584-b0a7-4069-8851-0ee7f9e18267",
            "name": "asdfadf",
            "properties": {
                "shape": null,
                "units": "gms",
                "dimension": null,
                "maxWeight": "sdf",
                "minWeight": "asfd"
            },
            "createdAt": "2021-06-11T15:19:07.387Z",
            "updatedAt": "2021-06-11T15:19:07.387Z",
            "farmId": "703ab269-20f5-4dca-8687-e14de5f6a4cb"
        }
    ]
}

并返回值如:

<br>
    <b-row>
    <b-col class="underline">My Grades</b-col>
    </b-row>
    <br>
    <div v-if="grades.length > 0">
    <b-card-group class="mb-4" v-for="grade in grades" :key="grade.id">
      <b-card :title="getTitle(grade)">
        <b-card-text class="list-card">
        

           
          {{getProperties(grade)}}
        
    

          <span style="float:right">
            <b-button
              class="mr-1"
              v-b-modal.modalConfirmDelete
              type="submit"
              variant="primary"
              size="sm"
            >
              <b-icon icon="map" size="is-small"></b-icon>
            </b-button>
            <b-button
              class="mr-1"
              type="reset"
              variant="danger"
              @click="actionDelete(grade.id)" 
              size="sm"
            >
              <b-icon icon="trash-fill" size="is-small"></b-icon>
            </b-button>
            <b-modal id="modalConfirmDelete" title="BootstrapVue">
                ddd
            </b-modal>
          </span>
        </b-card-text>
      </b-card>
    </b-card-group>

我尝试了一些类似 map、this below 和 join 的东西,但没有任何效果,因为 json 中的属性都是 diff,也尝试了带有长度的 for 循环。

getProperties(grade) {
      if (grade) {
         for (const [key, value] of Object.entries(grade)) {
            return `key: ${key}, value: ${value}`
          }
          
         }
      }
    },

只需要属性,在此先感谢

【问题讨论】:

  • 请您澄清一下,getProperties 函数的 期望输出 是什么?您想要 grade 中每个条目的 properties 属性吗?你想要什么格式的?
  • 对不起,我只需要它一个年级,但它会循环遍历所有不为空的属性,输出将是一个字符串,例如:Weight: 20, MaxDimension: 30, Extra: blablablabla , 所以无论是在单一等级的属性中

标签: javascript json vue.js object bootstrap-vue


【解决方案1】:

是你要找的吗?

var jsonData = JSON.parse('{"grade":[{"alias":"G1","id":"4d72868e-c46f-41d1-83a6-429a2421fd34","name":"Grade 1","properties":{"size":"A1","dimensions":"2x2","maturity_weight":"150"},"createdAt":"2020-03-30T09:57:24.756Z","updatedAt":"2020-03-30T09:57:24.756Z","farmId":"703ab269-20f5-4dca-8687-e14de5f6a4cb"},{"alias":"G2","id":"62fbefef-3342-43aa-8ed3-ed2ff0ff7cd6","name":"Grade 2","properties":{"size":"A2","dimensions":"3x3","maturity_weight":"150"},"createdAt":"2020-11-22T13:29:42.461Z","updatedAt":"2020-11-22T13:29:42.461Z","farmId":"703ab269-20f5-4dca-8687-e14de5f6a4cb"},{"alias":"G3","id":"9ce20ee1-c197-4775-97cb-35998ce51d4b","name":"Grade 3","properties":{"size":"A3","dimensions":"4x4","maturity_weight":"150"},"createdAt":"2020-11-22T13:31:16.955Z","updatedAt":"2020-11-22T13:31:16.955Z","farmId":"703ab269-20f5-4dca-8687-e14de5f6a4cb"},{"alias":"G4","id":"83f6ff4b-ab75-4930-ab84-59763b24d435","name":"Grade 4","properties":{"size":"A4","dimensions":"4x4","maturity_weight":"150"},"createdAt":"2020-11-22T13:31:16.955Z","updatedAt":"2020-11-22T13:31:16.955Z","farmId":"703ab269-20f5-4dca-8687-e14de5f6a4cb"},{"alias":"G5","id":"8dea25be-93e3-4ab4-ae58-685e4ab05dbf","name":"Grade 5","properties":{"units":"gms","maxWeight":"170","minWeight":"100"},"createdAt":"2020-08-11T08:52:23.484Z","updatedAt":"2020-08-11T08:52:23.484Z","farmId":"703ab269-20f5-4dca-8687-e14de5f6a4cb"},{"alias":"G6","id":"85aa81e4-b428-44d5-9ee2-4215de6c8226","name":"Grade 6","properties":null,"createdAt":"2020-05-15T09:53:23.809Z","updatedAt":"2020-05-15T09:53:23.809Z","farmId":"703ab269-20f5-4dca-8687-e14de5f6a4cb"},{"alias":"SG","id":"f4cd4ec4-1b99-42b1-839b-cd18c54d1761","name":"some grade","properties":{"shape":"","units":"gms","dimension":"","maxWeight":"2","minWeight":"1"},"createdAt":"2021-06-11T15:10:39.102Z","updatedAt":"2021-06-11T15:10:39.102Z","farmId":"703ab269-20f5-4dca-8687-e14de5f6a4cb"},{"alias":"SO","id":"ef862161-e3e9-4b84-9164-178a600a15a8","name":"som","properties":{"shape":null,"units":"gms","dimension":null,"maxWeight":"3","minWeight":"2"},"createdAt":"2021-06-11T15:18:16.460Z","updatedAt":"2021-06-11T15:18:16.460Z","farmId":"703ab269-20f5-4dca-8687-e14de5f6a4cb"},{"alias":"AS","id":"4a4e1584-b0a7-4069-8851-0ee7f9e18267","name":"asdfadf","properties":{"shape":null,"units":"gms","dimension":null,"maxWeight":"sdf","minWeight":"asfd"},"createdAt":"2021-06-11T15:19:07.387Z","updatedAt":"2021-06-11T15:19:07.387Z","farmId":"703ab269-20f5-4dca-8687-e14de5f6a4cb"}]}');

new Vue({
  el: '#app',
  data() { return {
      grades: jsonData.grade,
    }
  },
});
<link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap@4/dist/css/bootstrap.min.css" /><link type="text/css" rel="stylesheet" href="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.css" /><script src="//unpkg.com/vue@2/dist/vue.min.js"></script><script src="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue.min.js"></script><script src="//unpkg.com/bootstrap-vue@latest/dist/bootstrap-vue-icons.min.js"></script>

<div id="app">
  <b-row>
    <b-col class="underline">My Grades</b-col>
  </b-row>
  <br>
  <div v-if="grades.length > 0">
    <b-card-group class="mb-4" v-for="grade in grades" :key="grade.id">
      <b-card :title="grade.name">
        <b-card-text v-for="[key, value] in Object.entries(grade.properties != null ? grade.properties : {})" :key="key" class="list-card">
          {{ `${key}: ${value}` }}
          <span style="float:right">
              <b-button
                class="mr-1"
                v-b-modal.modalConfirmDelete
                type="submit"
                variant="primary"
                size="sm"
              >
                <b-icon icon="map" size="is-small"></b-icon>
              </b-button>
              <b-button
                class="mr-1"
                type="reset"
                variant="danger"
                @click="actionDelete(grade.id)" 
                size="sm"
              >
                <b-icon icon="trash-fill" size="is-small"></b-icon>
              </b-button>
              <b-modal id="modalConfirmDelete" title="BootstrapVue">
                  ddd
              </b-modal>
            </span>
        </b-card-text>
      </b-card>
    </b-card-group>
  </div>
</div>

我所做的主要更改是将getProperties 替换为v-for,因为在表格中显示多行需要grade.properties 中的每个属性都有一个新的HTML 元素。

对于那个v-for,我正在循环Object.entries(grade.properties ?? {})

  • Object.entries() 将为对象中的每个属性返回一个 [key, value] 数组,让我们可以轻松地显示两者。
  • grade.propertiesnullundefined 时,grade.properties ?? {} 只返回一个空对象{}。这样可以避免给Object.entries() 提供无效值,如果您使用null/undefined 调用它会引发错误。
    • 如果您的设置不支持 ?? 运算符,那么这也足够了:
      grade.properties != null ? grade.properties : {}

(我也直接将getTitle(grade)替换为grade.name,但这更多的是偏好问题。)

【讨论】:

  • 太棒了!谢谢,现在就试试!很好的解释:)
  • 无效的表达式:意外的令牌'?' in Object.entries(grade.properties ?? {}) 原始表达式:v-for="[key, value] in Object.entries(grade.properties ?? {})" 105| 106| 107| | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ^^^^^^^^^^^^^ 108| {{${key}: ${value}}} 109|
  • 出现错误。对于问号,我不知道它是不是 eslint,或者它说的是发出的值而不是实例错误
  • json 数据在我的数据中作为 Grades[],所以我将它放在一个对象数组中,并从 postgres 填充它
  • 谢谢一百万,现在要检查一下,有人在我发布的前一个问题中回答了它,它现在似乎工作了,但我需要调整它,所以也会检查你的,它可能会更有活力!谢谢:)
【解决方案2】:

我无法从 getProperties 函数中找出你想要的东西,但这有帮助吗?

const grade1 = {"alias": "G1","id": "4d72868e-c46f-41d1-83a6-429a2421fd34","name": "Grade 1","properties": {"size": "A1","dimensions": "2x2","maturity_weight": "150"},"createdAt": "2020-03-30T09:57:24.756Z","updatedAt": "2020-03-30T09:57:24.756Z","farmId": "703ab269-20f5-4dca-8687-e14de5f6a4cb"};
const grade2 = {"alias": "G6","id": "85aa81e4-b428-44d5-9ee2-4215de6c8226","name": "Grade 6","properties": null,"createdAt": "2020-05-15T09:53:23.809Z","updatedAt": "2020-05-15T09:53:23.809Z","farmId": "703ab269-20f5-4dca-8687-e14de5f6a4cb"};
const grade3 = {"alias": "SG","id": "f4cd4ec4-1b99-42b1-839b-cd18c54d1761","name": "some grade","properties": {"shape": "","units": "gms","dimension": "","maxWeight": "2","minWeight": "1"},"createdAt": "2021-06-11T15:10:39.102Z","updatedAt": "2021-06-11T15:10:39.102Z","farmId": "703ab269-20f5-4dca-8687-e14de5f6a4cb"};
const grade4 = {"alias": "SO","id": "ef862161-e3e9-4b84-9164-178a600a15a8","name": "som","properties": {"shape": null,"units": "gms","dimension": null,"maxWeight": "3","minWeight": "2"},"createdAt": "2021-06-11T15:18:16.460Z","updatedAt": "2021-06-11T15:18:16.460Z","farmId": "703ab269-20f5-4dca-8687-e14de5f6a4cb"};

// this function is used in getProperties
function keyValString(obj) {
  // reduce the output to one string
  return Object.entries(obj).reduce((str, [key, value], index) => { // for each key and value
    if (value) { // if value is not null or an empty string
      if (str) str += ", "; // if there is already text, add a comma and space
      str += `${key}: ${value}`; // add on the key and value
    }
    return str; // keep the string for the next loop
  }, "" /* <--- this empty string is the start value for our reduce operation */);
}

function getProperties(grade) {
  // if grade not null, and grade.properties not null, use keyValString(grade.properties) else use "No properties on grade."
  return (grade && grade.properties && keyValString(grade.properties)) || "No properties on grade."; // to instead return null, just replace the string with null
}

console.log( getProperties(grade1) );
console.log( getProperties(grade2) );
console.log( getProperties(grade3) );
console.log( getProperties(grade4) );
.as-console-wrapper {min-height:100%} /* format the console output */

【讨论】:

  • 嗨,对不起,我刚刚说我尝试了一个函数,但没有运气,好吧我试过了,但我不能解释什么。我确实需要:如果等级有任何属性,则显示该属性的名称和值,如果有意义,等级可以有很多或没有属性,因此通过等级中的每个等级对象,我需要提取属性并显示它们可以就像额外的,重量,大小,形状,除了单个值之外的任何东西,所以它是一个输入字段,所以额外的是一些描述的字符串或大小将是 150cm2 或类似的东西,如果这有意义的话,对不起,我自己对此感到困惑待
  • 所以最终返回值将是例如 Size: 20, Extra: This is important, Shape: Triangle, WeightMin: 4cm, or so from all keys and values from the grade object properties我将它放在前端的 for 循环中,所以我只需要 1 级属性即可通过它们并显示键和值
  • 如果有道理对不起@LaytonGB
  • 有道理,我会在有时间和评论时编辑我的答案,让您知道它已经完成。
  • 我已经更新了我的代码,我希望这是你所追求的。
猜你喜欢
  • 2016-10-24
  • 2021-10-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多