简体   繁体   English

JS 遍历 object 数组并将值更改为匹配键并创建一个新的 object 包含来自 object 数组的键[0]

[英]JS iterate through an object array and change the value to the matching key & create a new object containing the keys from the object array[0]

Goal:目标:

I have a table, a object array (props.data).我有一张桌子,一个 object 数组(props.data)。 I need to get the value from each object and display them on their respective rows.我需要从每个 object 中获取值并将它们显示在各自的行上。 However I can not copy them straight from props.data as I need to attach some key pair attributes to each column (dataField, text, filter, sort, hidden).但是我不能直接从 props.data 复制它们,因为我需要将一些密钥对属性附加到每一列(数据字段、文本、过滤器、排序、隐藏)。


What's working:什么工作:

It appears the rows are being handled correctly.看来行正在正确处理。 I confirm this by printing the object array that holds the rows before it gets used by the table and it has all the data the way I require it.我通过打印 object 数组来确认这一点,该数组在表格使用之前保存行,并且它具有我需要的所有数据。


What's not working:什么不起作用:

The column data which is extracted from props.data is missing columns/data and has some incorrect values that should have been changed and extracted in my code snippet down below.从 props.data 提取的列数据缺少列/数据,并且有一些不正确的值,应该在下面的代码片段中更改和提取。


Current code:当前代码:


 function store_file_name(event) {
    localStorage.setItem('file_name', event.target.innerHTML);
  }
  //This handles the setting for each column 
  var columns = []
  var index = 0
  props.data.map(data => {
    // this handles the default refinemnet toggles. From prop default_refine_toggle_display. The prop object array string names needs to have the column name post name_name
    var hidden_status = true
    default_refine_toggle_display.forEach(element => {
      if (Object.keys(data)[index] == element) {
        hidden_status = false
      }
    });


    //FIXME: This will add a link to th efile viewer page as well as store the name as a localstorage which is then used by the file viewer page to as the path to get the file that the user wants to view.
    if (Object.keys(data)[index] == "CV") {//FIXME: This only find the CV for ID 11? And then fires a few times for the same ID
      console.log("The Column key:", Object.keys(data)[index])
      console.log("The Column Value:", Object.values(data)[index])
      console.log("this is meant to be key pair: ", data[index])
      data.CV = <a onClick={store_file_name} className="link" href="/file_viewer" > {data.CV}</a>
    }
    // FIXME:  Why are we not getting all the columns pushed? There as some getting missed such as "job title name"
    columns.push(
      {
        dataField: Object.keys(data)[index],
        text: Object.keys(data)[index],
        filter: textFilter({
          getFilter: filter => {
            filter_array.push(filter);
          }
        }),
        sort: true,
        hidden: hidden_status
      }
    )
    index++
  })
  console.log("COLUMNS, CURRENT RESULT:", columns)
  console.log("props.data, CURRENT RESULT:", props.data)


Current outcome:目前的结果:

  1. Not all the keys are getting put into the new object array "columns".并非所有键都放入新的 object 数组“列”中。 when it should as far as i can tell all the keys are getting mapped over and pushed.据我所知,当它应该被映射并按下时。
  2. Only one of the rows is having the added, when this should be added to all rows as all rows will have that matching key.只有其中一行被添加,当这应该被添加到所有行时,因为所有行都将具有该匹配键。
Columns =
[
  {
    "dataField": "ID",
    "text": "ID",
    "filter": {
      "props": {}
    },
    "sort": true,
    "hidden": false
  },

  {
    "dataField": "First",
    "text": "First",
    "filter": {
      "props": {}
    },
    "sort": true,
    "hidden": false
  },

  {
    "dataField": "Middle",
    "text": "Middle",
    "filter": {
      "props": {}
    },
    "sort": true,
    "hidden": false
  },

  {
    "dataField": "Last",
    "text": "Last",
    "filter": {
      "props": {}
    },
    "sort": true,
    "hidden": false
  },

  {
    "dataField": "Job Listing ID",
    "text": "Job Listing ID",
    "filter": {
      "props": {}
    },
    "sort": true,
    "hidden": true
  },

  {
    "dataField": "Recruiter ID",
    "text": "Recruiter ID",
    "filter": {
      "props": {}
    },
    "sort": true,
    "hidden": true
  },

  {
    "dataField": "CV",
    "text": "CV",
    "filter": {
      "props": {}
    },
    "sort": true,
    "hidden": false
  },

  {
    "dataField": "C Letter",
    "text": "C Letter",
    "filter": {
      "props": {}
    },
    "sort": true,
    "hidden": false
  },

  {
    "dataField": "NDA",
    "text": "NDA",
    "filter": {
      "props": {}
    },
    "sort": true,
    "hidden": false
  },

  {
    "dataField": "Photo",
    "text": "Photo",
    "filter": {
      "props": {}
    },
    "sort": true,
    "hidden": false
  },

  {
    "dataField": "Address",
    "text": "Address",
    "filter": {
      "props": {}
    },
    "sort": true,
    "hidden": false
  },

  {
    "dataField": "Sex",
    "text": "Sex",
    "filter": {
      "props": {}
    },
    "sort": true,
    "hidden": true
  },

  {
    "dataField": "Email",
    "text": "Email",
    "filter": {
      "props": {}
    },
    "sort": true,
    "hidden": true
  },

  {
    "dataField": "Building #",
    "text": "Building #",
    "filter": {
      "props": {}
    },
    "sort": true,
    "hidden": true
  },

  {
    "dataField": "Street #",
    "text": "Street #",
    "filter": {
      "props": {}
    },
    "sort": true,
    "hidden": true
  },
{
    "dataField": "Street Name",
    "text": "Street Name",
    "filter": {
      "props": {}
    },
    "sort": true,
    "hidden": true
  },

  {
    "dataField": "Town Name",
    "text": "Town Name",
    "filter": {
      "props": {}
    },
    "sort": true,
    "hidden": true
  },

  {
    "dataField": "State",
    "text": "State",
    "filter": {
      "props": {}
    },
    "sort": true,
    "hidden": true
  },

  {
    "dataField": "Country",
    "text": "Country",
    "filter": {
      "props": {}
    },
    "sort": true,
    "hidden": true
  },

  {
    "dataField": "Status ID",
    "text": "Status ID",
    "filter": {
      "props": {}
    },
    "sort": true,
    "hidden": true
  },
{
    "dataField": "Change Datetime",
    "text": "Change Datetime",
    "filter": {
      "props": {}
    },
    "sort": true,
    "hidden": true
  },

  {
    "dataField": "Why Should We",
    "text": "Why Should We",
    "filter": {
      "props": {}
    },
    "sort": true,
    "hidden": true
  }
]
props.data [{
  "ID": 5,

  "First": "first",

  "Middle": null,

  "Last": "last",

  "Job Listing ID": null,

  "Recruiter ID": null,

  "CV": "null",

  "C Letter": "null",

  "NDA": null,

  "Photo": null,

  "Address": null,

  "Sex": null,

  "Email": "test@outlook.com",

  "Building #": null,

  "Street #": null,

  "Street Name": null,

  "Town Name": null,

  "State": null,

  "Country": "Australia",

  "Status ID": 1,

  "Change Datetime": "1899-12-31T14:00:00.000Z",

  "Why Should We": null,

  "Submitted_datetime": null,

  "Accepted_datetime": null,

  "Rejected_datetime": null,

  "Pending_datetime": null,

  "Completed_datetime": null,

  "job_title_id": null,

  "Created_datetime": null,

  "required_amount": null,

  "ended_datetime": null,

  "description": "Submitted, waiting for review",

  "required_skills": null,

  "Job_title_name": null,

  "salary_base_id": null,

  "name": "Submitted"
}

{etc..},
etc...
]


Desired outcome期望的结果

columns should = the same as above but not be missing any of the keys from props.data 

props.data should = the same as above but should have all the "CV" values be wrapped in <a></a>

I am trying to map a object array to get the key of each keypair of the first object (As the objects will all have the same keys) and use that key in a new object array as a value to the keys "dataField" and "text". I am trying to map a object array to get the key of each keypair of the first object (As the objects will all have the same keys) and use that key in a new object array as a value to the keys "dataField" and "文本”。

In the process of doing that I am trying to add some additional key pairs to each object such as "filter", "sort" and "hidden".在此过程中,我尝试为每个 object 添加一些额外的密钥对,例如“过滤器”、“排序”和“隐藏”。

Also, while I am doing this loop I am trying to change some of the values for the keys that match a string.此外,在执行此循环时,我正在尝试更改与字符串匹配的键的一些值。 All the keys that match the string should have a "" wrapped around its value.与字符串匹配的所有键都应在其值周围有一个“”。


What I am thinking of changing我想改变什么

from what i can tell, it should already be working.据我所知,它应该已经开始工作了。 Though to make things cleaner, I am thinking to separate the two tasks.虽然为了使事情更清洁,但我正在考虑将这两个任务分开。 I am thinking to get the keys from props.data[0] from Object.keys, and store them in a string array.我正在考虑从 Object.keys 的 props.data[0] 中获取密钥,并将它们存储在字符串数组中。 Then run a foreach on that array to make a object that can hold the key pairs needs for the columns.然后在该数组上运行一个 foreach 以生成一个 object 可以保存列所需的密钥对。

I am puzzled on how to go about adding the to the matching keys on each object.我对如何将 go 添加到每个 object 上的匹配键感到困惑。

Could I please have help getting my desired result?我可以帮助获得我想要的结果吗?

I solved this question by:我通过以下方式解决了这个问题:

Creating the columns:创建列:

  1. Separating the two functions.分离两个功能。
  2. Getting the column names by the Object keys通过 Object 键获取列名
  3. looping through each of those keys and store them with the required keypairs循环遍历每个密钥并将它们与所需的密钥对一起存储

Adding to the object array添加到 object 阵列

  1. Looped through each object and then each keypair in that object循环遍历每个 object,然后遍历该 object 中的每个密钥对
  2. Checked the value of the key pair against the string, and if it matched, then the change was made根据字符串检查密钥对的值,如果匹配,则进行更改

I am honestly not sure why this works over the other attempt I made.老实说,我不确定为什么这对我所做的其他尝试有效。

Could someone explain why this is working and the other wasn't?有人可以解释为什么这有效而另一个无效吗? And if there is a better way to do the below?如果有更好的方法来执行以下操作?

function set_up_columns(data) {
    var columns = []
    var column_names = Object.keys(data[0])
    column_names.forEach(element => {
      var hidden_status = true

      default_refine_toggle_display.forEach(element_ => {// this sets the hidden attribute/value. It will mark as false if the 
        if (element == element_) {
          hidden_status = false
        }
      });
      columns.push(
        {
          dataField: element,
          text: element,
          filter: textFilter({
            getFilter: filter => {
              filter_array.push(filter);
            }
          }),
          sort: true,
          hidden: hidden_status
        }
      )
    });
    return columns
  }

  var columns = set_up_columns(props.data)
function add_view_file_to_column_values(data){
    var number_of_columns_and_keypairs = Object.keys(data[0]).length//this gets thesize of the object
    data.map(data_ => {
      //each run of this is a row
      for (let index = 0; index < number_of_columns_and_keypairs; index++) {
        //each run of this is a column in that row
        if (Object.keys(data_)[index] == "CV") {
          console.log("data", Object.keys(data_)[index])
          data_[Object.keys(data_)[index]] = <a onClick={store_file_name} className="link" href="/file_viewer" > {Object.values(data_)[index]}</a>
        }
      }
    })
    return data
  }
 
  props.data =  add_view_file_to_column_values(props.data)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 遍历对象数组并创建一个新对象 - Iterate through a array of objects and create a new object JavaScript - 如何遍历对象数组以创建一个新对象,其键是原始对象的初始键/值对的值 - JavaScript — how to iterate through an array of objects to create a new object whose key is the value of the original object's initial key/value pair 遍历JS对象/数组,如果找到匹配项,则更改值并返回原始对象/数组结构 - Iterate through JS object/array, and if you find a match change the value and return the original object/array structure 将对象键值迭代为数组 - iterate object key value as an array 从具有相同键的对象创建一个新数组 - Create a new array from object with same keys 将数字键分配给JS对象,vm是否认为我正在索引到数组中而从0到该值创建键? - Assigning numeric key to a JS object, does vm create keys from 0 to that value thinking that I'm indexing into an array? 如何创建新的 object 从另一个 object 数组迭代 - how to create new object iterate from another array of object Svelte 迭代键数组并从对象中获取键 - Svelte iterate over array of keys and get key from object 遍历 object 的数组并更改 object 的值 - Iterate over an array of object and change object value 将JS对象数组推送到具有匹配对象键的另一个对象数组 - Push JS object array to another object array with matching object key
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM