【问题标题】:Push an Object Into a complicated arra将对象推入复杂的阵列
【发布时间】:2020-08-05 07:29:15
【问题描述】:

我正在尝试将一个对象推入一个复杂的数组中,我正在考虑类似“DUMMY_PLACES[0].todos.byIds.push”之类的东西,但我没有成功。我有一个(id,content),并且完成需要默认为false。希望得到帮助我相信这并不太复杂,但我无法弄清楚。 ps:如果有人也可以帮助删除选项,我会很高兴。

例如,我得到 (5,test5)。我要。

     const DUMMY_PLACES = [
          {
            todos: {
              allIds: [1, 2, 3, 4,],
              byIds: {
                "1": {
                  content: "test1",
                  completed: false,
                },
                "2": {
                  content: "test2",
                  completed: false,
                },
                "3": {
                  content: "test3\\",
                  completed: false,
                },
                "4": {
                  content: "test4",
                  completed: false,
                },
              },
            },
            visibilityFilter: "all",
          },
        ];

 const DUMMY_PLACES = [
      {
        todos: {
          allIds: [1, 2, 3, 4,5],
          byIds: {
            "1": {
              content: "test1",
              completed: false,
            },
            "2": {
              content: "test2",
              completed: false,
            },
            "3": {
              content: "test3\\",
              completed: false,
            },
            "4": {
              content: "test4",
              completed: false,
            },
            "5": {
              content: "test5",
              completed: false,
            },
          },
        },
        visibilityFilter: "all",
      },
    ];

【问题讨论】:

  • 你想推什么?
  • 需要推入复杂数组的Object在哪里?
  • 这里的主要问题似乎是您存储数据的方式。
  • 我同意@baao这里
  • @Ethanolle 这与意见或观点无关。 todos 应该是一个数组,将 byIds 所做的(现在错误地作为对象)保存为数组而不是对象,而 allIds 完全没有必要

标签: javascript arrays push


【解决方案1】:

这里看一下addTodo 函数,它创建todoList 的新实例,并在其末尾添加了一个新元素。它还修改了Ids 的列表。我几乎对每一行都进行了评论,所以应该很简单。

let todoList = [
  {
    todos: {
      allIds: [1, 2, 3, 4],
      byIds: {
        "1": {
          content: "test1",
          completed: false,
        },
        "2": {
          content: "test2",
          completed: false,
        },
        "3": {
          content: "test3",
          completed: false,
        },
        "4": {
          content: "test4",
          completed: false,
        },
      },
    },
    visibilityFilter: "all",
  },
];

let addTodo = (sourceArray, el) => {
  // Create a copy of an original array
  let targetArray = [];
  Object.assign(targetArray, sourceArray);

  let todos = targetArray[0].todos;

  // Calculate the Id for a new element
  let newId = Object.keys(todos.byIds).length + 1;

  // Add new Id to the `allIds` list
  todos.allIds.push(newId);

  // Create a new element
  todos.byIds[newId] = {
    content: el,
    completed: false
  }

  return targetArray;
}

todoList = addTodo(todoList, 'test5');
todoList = addTodo(todoList, 'test6');
todoList = addTodo(todoList, 'test7');

console.log(JSON.stringify(todoList));

输出应该是:

[
  {
    "todos":{
      "allIds":[
        1,
        2,
        3,
        4,
        5,
        6,
        7
      ],
      "byIds":{
        "1":{
          "content":"test1",
          "completed":false
        },
        "2":{
          "content":"test2",
          "completed":false
        },
        "3":{
          "content":"test3",
          "completed":false
        },
        "4":{
          "content":"test4",
          "completed":false
        },
        "5":{
          "content":"test5",
          "completed":false
        },
        "6":{
          "content":"test6",
          "completed":false
        },
        "7":{
          "content":"test7",
          "completed":false
        }
      }
    },
    "visibilityFilter":"all"
  }
]

【讨论】:

    【解决方案2】:

    也许你需要这样的东西

    const DUMMY_PLACES = [ { todos: { allIds: [1, 2, 3, 4], byIds: { "1": { content: "test1", completed: false, }, "2": { content: "test2", completed: false, }, "3": { content: "test3\\", completed: false, }, "4": { content: "test4", completed: false, }, }, }, visibilityFilter: "all", }, ];
    
    function pushObject(id, content) {
      DUMMY_PLACES[0].todos.allIds.push(id);
      DUMMY_PLACES[0].todos.byIds[id] = { ...content, completed: false };
    }
    pushObject(5, { content: "test5" });
    console.dir(DUMMY_PLACES);

    【讨论】:

      【解决方案3】:

      您的代码缺少封装。这里最好的方法是创建一个新类并为此创建一个 setter。

      编辑示例:

      class UserTodo
      {
          constructor( visibilityFilter = 'all' )
          {
              this._visibilityFilter  = visibilityFilter;
              this._byIds             = new Map();
          }
          /**
           * @details Add a todo with the content text
           */
          addTodo( title, content )
          {
              const value = {
                  content,
                  completed: false
              }
              this._byIds.set( title, value );
          }
      
          /**
           * @Details Decide if you want to get the entire object or just the content here
           */
          getTodo( title )
          {
              return this._byIds.get( title );
          }
      
          completeTodo( title )
          {
              this._byIds.get( title ).completed  = true;
          }
      
          /**
           * @details As a bonus on how to delete a specific todo
           */
          deleteTodo( title )
          {
              this._byIds.delete( title );
          }
      
          /**
           * @details this will return allIds from the example
           */
          getAllIds()
          {
              return Array.from( this._byIds.keys() );
          }
      
          /**
           * @details this will return visibilityFilter from the example
           */
          getVisibility()
          {
              return this._visibilityFilter;
          }
      
          // Implement other getters
      }
      
      // Why is this an array even?
      const DUMMY_PLACES  = [];
      DUMMY_PLACES.push( new UserTodo( 'all' ) );
      
      const toDoTitle = 'Some Title';
      
      // Add a new todo
      DUMMY_PLACES[0].addTodo( toDoTitle, 'Do Something' );
      
      // Check that the todo is added
      console.log( DUMMY_PLACES[0].getTodo( toDoTitle ) );
      
      // Complete it
      DUMMY_PLACES[0].completeTodo( toDoTitle );
      
      // Check that it is completed
      console.log( DUMMY_PLACES[0].getTodo( toDoTitle ) );

      【讨论】:

      • 是的,我的回答保持不变。这段代码需要更好的封装。您正在尝试对一个非常复杂的对象执行相当复杂的操作。并且对象不应该以这种方式使用。检查我的编辑,看看你是否更喜欢这种方法。
      猜你喜欢
      • 2021-09-12
      • 1970-01-01
      • 2018-07-30
      • 2021-10-07
      • 2012-07-28
      • 2015-01-23
      • 1970-01-01
      • 1970-01-01
      • 2013-03-25
      相关资源
      最近更新 更多