Лучший способ преобразовать массив в javascript - PullRequest
0 голосов
/ 01 августа 2020

Я разрабатываю приложение для реагирования и получаю указанный ниже массив из вызова 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"
         } 
      ] 
   } 

Я хочу преобразовать этот массив, как показано ниже:

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' 
          } ]

Может кто-нибудь, пожалуйста, помогите мне, как это сделать? Я могу также изменить исходный массив, если это необходимо, поскольку я контролирую API. Сообщите мне, если потребуется дополнительная информация.

Ответы [ 5 ]

0 голосов
/ 01 августа 2020

Используйте Object.entreis, map, Object.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));
0 голосов
/ 01 августа 2020

Попробуйте это, это даст точный формат, который вы ищете (массив объектов).

Я использовал Set () в этом случае для удаления дубликатов, а затем использовал оператор распространения (... ), чтобы снова превратить его в массив со всеми уникальными объектами. Есть способы сделать то же самое с .reduce () и .filter (). Вот некоторые ресурсы, которые могут быть полезны.

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://www.w3schools.com/jsref/jsref_reduce.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))
0 голосов
/ 01 августа 2020

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)

Изменить: обновлено с помощью сниппета!

0 голосов
/ 01 августа 2020

Вы можете попробовать манипуляции с массивом с помощью map, reduce.

Нижеприведенный фрагмент может помочь

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)
0 голосов
/ 01 августа 2020

Вы можете просто перебирать массив и извлекать нужные вам части. Если ваши входящие данные находятся в 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
})
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...