如何分割字符串并从数组转换为对象 [英] How to split a string and convert as a object from an array

查看:66
本文介绍了如何分割字符串并从数组转换为对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有字符串值的对象数组,其中第一个数组作为标题:

I have an array of objects with a string value in it, with a first array as an header:

var data = [{records : "productId*amount*tax1*tax2*tax3"},
            {records : "111*2000*10*12*13"},
            {records : "113*3000*10**"}]

我需要通过使用data [0]作为键,而将data [x]的其余部分作为其值,将此对象数组转换为具有键-值对的单个对象.

I need to convert this array of objects into an individual objects with key-value pairs by using the data[0] as key and rest of the data[x] as its value .

预期输出:

data: [
  {
     "productId" : "111",
     "amount" : '2000",
     "tax1" : "10",
     "tax2" : "12",
     "tax3" : "13"
  },
  {
     "productId" : "113",
     "amount" : "3000",
     "tax1" : "10",
     "tax2" : "0",
     "tax3" : "0"
  }
]

我可以使用split运算符拆分字符串并将其作为单个数组获取,但是无法弄清楚如何将其分配给数组中的键值对,因此我对JS非常陌生.

I can use the split operator to split the strings and get them as an individual array, but can't figure out how to assign it to key value pairs in an array and I'm very new to JS.

推荐答案

因此,您将第一个索引拆分为键.

So you split the first index into the keys.

您可以遍历其余部分,并使用索引键生成对象.

You loop over the remaining and generate the objects using the key for the index.

var data = [{
    records: "productId*amount*tax1*tax2*tax3"
  },
  {
    records: "111*2000*10*12*13"
  },
  {
    records: "113*3000*10**"
  }
]

// grab the keys from first record
var keys = data.shift().records.split("*")

// loop over the rest of the records
var result = data.reduce(function(arr, item) {
  // split up the records
  const rec = item.records.split("*").reduce(function(obj, value, index) {
    // grab the key for the index
    var key = keys[index]
    // set the object with the key and the value
    obj[key] = value
    // return back the updated object
    return obj
  }, {})
  // add the object to the array
  arr.push(rec)
  return arr
}, [])
console.log(result);

这篇关于如何分割字符串并从数组转换为对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆