简体   繁体   English

在 javascript 中转换数组的最佳方法

[英]Best way to convert array in javascript

I am developing a react app, and I am getting the below array from a api call.我正在开发一个反应应用程序,我从 api 调用中获取以下数组。

var arrayLike ={ 
         "2020-W1": [
         { 
            "type": "TAX_REFUND_IN_INT", 
            "net_amount_base": "500001"
         },
         { 
            "type": "TAX_REFUNDIN_IN_EXT", 
            "net_amount_base": "500002"
         }
      ],
      "2020-W2": [
         { 
            "type": "RENTAL_LEASING_INCOME_IN_INT", 
            "net_amount_base": "5000"
         },
         { 
            "type": "DIVIDENTS_INCOME_IN_INT", 
            "net_amount_base": "15000"
         },
         { 
            "type": "LICENCE_INCOME_IN_EXT", 
            "net_amount_base": "10000"
         },
         { 
            "type": "OTHER_INCOME_IN_EXT", 
            "net_amount_base": "1000"
         } 
      ] 
   } 

I want to convert this array like below:我想像下面这样转换这个数组:

var new_arr =  var new_arr =  [{
            year_week: '2020-W1',
            TAX_REFUND_IN_INT: '1000',
            TAX_REFUNDIN_IN_EXT: '300' 
          },
          {
            year_week: '2020-W2',
            RENTAL_LEASING_INCOME_IN_INT: '2000',
            DIVIDENTS_INCOME_IN_INT: '15000',
            LICENCE_INCOME_IN_EXT: '10000',
            OTHER_INCOME_IN_EXT: '1000' 
          } ]

Can someone please help me how to do this?有人可以帮我怎么做吗? I can change the source array also if required since I have control over the API.Please let me know if any more information is required.如果需要,我也可以更改源数组,因为我可以控制 API。如果需要更多信息,请告诉我。

You can just iterate over the array, and pull out the parts that you want.您可以只遍历数组,然后取出您想要的部分。 If your incoming data is in actual_arr如果您的传入数据在actual_arr

var actual_arr = {
  "2020-W1" :{
  0: {site_id: "004", year_week: "2020-W1", type: "RENTAL_LEASING_INCOME", in_out: "IN", int_ext: "INT","amount" :1000},
  1: {site_id: "004", year_week: "2020-W1", type: "DIVIDENTS_INCOME", in_out: "IN", int_ext: "INT","amount" :300},
  2: {site_id: "004", year_week: "2020-W1", type: "LICENCE_INCOME", in_out: "IN", int_ext: "INT","amount" :20},
  3: {site_id: "004", year_week: "2020-W1", type: "OTHER_INCOME", in_out: "IN", int_ext: "INT","amount" :100 },
  },
 }



const new_arr = Object.keys(actual_arr).map(key=> {
  // Build an object to receive the values
  const object = {year_week: key}
   Object.keys(actual_arr[key]).forEach(ix => {
     const income_name = actual_arr[key][ix].type
     const income_amount = actual_arr[key][ix].amount
      object[income_name] = income_amount
  })
  return object
})

 var arrayLike = { "2020-W1": [{ "type": "TAX_REFUND_IN_INT", "net_amount_base": "500001" }, { "type": "TAX_REFUNDIN_IN_EXT", "net_amount_base": "500002" } ], "2020-W2": [{ "type": "RENTAL_LEASING_INCOME_IN_INT", "net_amount_base": "5000" }, { "type": "DIVIDENTS_INCOME_IN_INT", "net_amount_base": "15000" }, { "type": "LICENCE_INCOME_IN_EXT", "net_amount_base": "10000" }, { "type": "OTHER_INCOME_IN_EXT", "net_amount_base": "1000" } ] } let newArray = [] Object.values(arrayLike).forEach((arr, index) => { let newObj = {} newObj['yearWeek'] = Object.keys(arrayLike)[index] arr.forEach((item) => { newObj[`${item.type}`] = item.net_amount_base }) newArray.push(newObj) }) console.log(newArray)

Edit: Updated with a snippet!编辑:更新了一个片段!

You could try some array manipulation with map , reduce .您可以尝试使用map进行一些数组操作, reduce

Below snippet could help下面的片段可能会有所帮助

 const arr = { "2020-W1": { 0: { site_id: "004", year_week: "2020-W1", type: "RENTAL_LEASING_INCOME", in_out: "IN", int_ext: "INT", amount: 1000 }, 1: { site_id: "004", year_week: "2020-W1", type: "DIVIDENTS_INCOME", in_out: "IN", int_ext: "INT", amount: 300 }, 2: { site_id: "004", year_week: "2020-W1", type: "LICENCE_INCOME", in_out: "IN", int_ext: "INT", amount: 20 }, 3: { site_id: "004", year_week: "2020-W1", type: "OTHER_INCOME", in_out: "IN", int_ext: "INT", amount: 100 }, }, "2020-W2": { 0: { site_id: "004", year_week: "2020-W2", type: "RENTAL_LEASING_INCOME", in_out: "IN", int_ext: "INT", amount: 2000 }, 1: { site_id: "004", year_week: "2020-W2", type: "DIVIDENTS_INCOME", in_out: "IN", int_ext: "INT", amount: 400 }, 2: { site_id: "004", year_week: "2020-W2", type: "LICENCE_INCOME", in_out: "IN", int_ext: "INT", amount: 2000 }, 3: { site_id: "004", year_week: "2020-W2", type: "OTHER_INCOME", in_out: "IN", int_ext: "INT", amount: 5000 }, }, "2020-W3": { 0: { site_id: "004", year_week: "2020-W3", type: "RENTAL_LEASING_INCOME", in_out: "IN", int_ext: "INT", amount: 1000 }, 1: { site_id: "004", year_week: "2020-W3", type: "DIVIDENTS_INCOME", in_out: "IN", int_ext: "INT", amount: 2000 }, 2: { site_id: "004", year_week: "2020-W3", type: "LICENCE_INCOME", in_out: "IN", int_ext: "INT", amount: 3000 }, 3: { site_id: "004", year_week: "2020-W3", type: "OTHER_INCOME", in_out: "IN", int_ext: "INT", amount: 4000 }, }, } const res = Object.keys(arr).map((year_week) => { const typeAmounts = Object.keys(arr[year_week]).reduce( (acc, index) => ({...acc, [arr[year_week][index].type]: arr[year_week][index].amount, }), {} ) return { year_week, ...typeAmounts, } }) console.log(res)

Try this, this gives the exact format that you are looking for (an Array of Objects).试试这个,这给出了您正在寻找的确切格式(对象数组)。

I used Set() in this case to remove duplicates and then used the spread operator (...) to turn it back into an array with all the unique objects.在这种情况下,我使用 Set() 删除重复项,然后使用扩展运算符 (...) 将其转换回包含所有唯一对象的数组。 There are ways to do the same thing with.reduce() and.filter() as well.也有一些方法可以用 .reduce() 和 .filter() 做同样的事情。 Here are some resources that may be helpful.以下是一些可能有用的资源。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/Set https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set/Set

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax

https://www.w3schools.com/jsref/jsref_reduce.asp https://www.w3schools.com/jsref/jsref_reduce.asp

https://www.w3schools.com/jsref/jsref_filter.asp https://www.w3schools.com/jsref/jsref_filter.asp

 let arrayLike = { "2020-W1": [{ "type": "TAX_REFUND_IN_INT", "net_amount_base": "500001" }, { "type": "TAX_REFUNDIN_IN_EXT", "net_amount_base": "500002" } ], "2020-W2": [{ "type": "RENTAL_LEASING_INCOME_IN_INT", "net_amount_base": "5000" }, { "type": "DIVIDENTS_INCOME_IN_INT", "net_amount_base": "15000" }, { "type": "LICENCE_INCOME_IN_EXT", "net_amount_base": "10000" }, { "type": "OTHER_INCOME_IN_EXT", "net_amount_base": "1000" } ] } function solveProblem(arrayLike) { let final_array = [] let newObjectOne = {} let newObjectTwo = {} for (i in arrayLike) { for (z in i) { if (i === "2020-W1") { if (arrayLike[i][z],== undefined) { newObjectOne["year_week"] = "2020-W1". newObjectOne[arrayLike[i][z].type] = arrayLike[i][z].net_amount_base final_array,push(newObjectOne) } } if (i === "2020-W2") { if (arrayLike[i][z].== undefined) { newObjectTwo["year_week"] = "2020-W2". newObjectTwo[arrayLike[i][z].type] = arrayLike[i][z].net_amount_base final_array.push(newObjectTwo) } } } } let unqiueItemsArr = new Set(final_array) return [...unqiueItemsArr] } //console.log(solveProblem(arrayLike)) to see new array of objects console.log(solveProblem(arrayLike))

Use Object.entreis , map , Object.fromEntries to convert.使用Object.entreismapObject.fromEntries进行转换。

 const convert = data => Object.entries(data).map(([year_week, arr]) => ({ year_week, ...Object.fromEntries(arr.map(Object.values)), })); var arrayLike = { "2020-W1": [ { type: "TAX_REFUND_IN_INT", net_amount_base: "500001", }, { type: "TAX_REFUNDIN_IN_EXT", net_amount_base: "500002", }, ], "2020-W2": [ { type: "RENTAL_LEASING_INCOME_IN_INT", net_amount_base: "5000", }, { type: "DIVIDENTS_INCOME_IN_INT", net_amount_base: "15000", }, { type: "LICENCE_INCOME_IN_EXT", net_amount_base: "10000", }, { type: "OTHER_INCOME_IN_EXT", net_amount_base: "1000", }, ], }; console.log(convert(arrayLike));

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM