【问题标题】:How to properly create objects instead of arrays in Javascript如何在Javascript中正确创建对象而不是数组
【发布时间】:2022-01-08 14:45:45
【问题描述】:

我正在尝试使用占位符创建一个对象。当前代码有效,但是它正在我的 Children 属性中创建数组。如何重新编码以便我的输出是对象

const placeholder = (index, isRootDirectory) => {
  const create = {
    id: index,
    title: null,
    location: index,
    isRootDirectory,
    padStyle: [
      {
        icon: null,
        color: null,
      },
    ],
    UUID: null,
    action: null,
    Children: [],
  };

  return create;
};

const createLayout = () => {
  let root = {
    info: "Custom Layout",
    Children: [],
  };

  for (let i = 0; i < 2; i++) {
    root.Children.push(placeholder(i, true));
    console.log(root);
  }

  console.log(root);
};


当前输出:

{"Children": [{"Children": [Array], "UUID": null, "action": null, "id": 0, "isRootDirectory": true, "location": 0, "padStyle": [Array], "title": null}, {"Children": [Array], "UUID": null, "action": null, "id": 1, "isRootDirectory": true, "location": 1, "padStyle": [Array], "title": null}], "info": "Custom Layout"}

期望的输出

{"Children": [{"Children": [object], "UUID": null, "action": null, "id": 0, "isRootDirectory": true, "location": 0, "padStyle": [object], "title": null}, {"Children": [object], "UUID": null, "action": null, "id": 1, "isRootDirectory": true, "location": 1, "padStyle": [object], "title": null}], "info": "Custom Layout"}

【问题讨论】:

标签: javascript arrays object


【解决方案1】:

在您定义常量create 的代码中,您通过编写Children: []Children 键定义为一个数组。相反,写Children: {}。 所以

const create = {
    id: index,
    title: null,
    location: index,
    isRootDirectory,
    padStyle: [
      {
        icon: null,
        color: null,
      },
    ],
    UUID: null,
    action: null,
    Children: [],
  };

应该写成

const create = {
    id: index,
    title: null,
    location: index,
    isRootDirectory,
    padStyle: [
      {
        icon: null,
        color: null,
      },
    ],
    UUID: null,
    action: null,
    Children: {},
  };

【讨论】:

    猜你喜欢
    • 2010-12-08
    • 2019-12-23
    • 1970-01-01
    • 2015-10-19
    • 2021-02-04
    • 1970-01-01
    • 2023-02-23
    • 2012-05-31
    相关资源
    最近更新 更多