将随机序列分组为对象数组

时间:2017-04-18 21:59:59

标签: javascript

我有一个文本文件,包含2种不同类型的数据:“NAMES”和“ACTIONS”,每种类型在整个文本文件中以随机顺序重复:

NAME: joe 
ACTION: running 
NAME: paul 
ACTION: walking 
ACTION: swimming 
NAME: mary 
NAME: joe 
ACTION: sleeping 
NAME: paul 
NAME: mary 
NAME: ken 
ACTION: jumping 
ACTION: running 
ACTION: eating

我正在尝试通过连接每种类型的数据来创建一个对象数组,这样每个对象只能保存一对NAMES和ACTIONS,如下所示:

{   
    “name”: joe,
    “action” : running
}

{   
    “name: paul,
    “action” : walking swimming 
}

{   
    “name: mary joe, 
    “action” : sleeping 
}

{   
    “name: paul mary ken, 
    “action” : jumping running eating 
}

到目前为止,我已经尝试使用一个简单的for循环逐行迭代文本文件,检查一行是否包含NAME或ACTION,但我无法弄清楚连接的逻辑并将值推送到数组中惹麻烦。我在学习javascript并且可以使用一点帮助解决这个问题,提前谢谢。

3 个答案:

答案 0 :(得分:0)

您需要先逐行拆分文本字符串,然后遍历每一行并解析键和值。这是一个有效的例子



var text = `NAME: joe 
ACTION: running 
NAME: paul 
ACTION: walking 
ACTION: swimming 
NAME: mary 
NAME: joe 
ACTION: sleeping 
NAME: paul 
NAME: mary 
NAME: ken 
ACTION: jumping 
ACTION: running 
ACTION: eating`

// split the text in to an array of lines
var lines = text.split("\n")

var data = [] // the final mapped data
var person = null // the person object to add actions to

// loop through each line
lines.forEach(function(line){
  
  // split the line into a key (NAME or ACTION) and the value
  var vals = line.split(': ')
  var key = vals[0]
  var val = vals[1]

  // if this line is for a new name, make a new "person"
  if( key == 'NAME' ){
  
    // save the current person to the final data
    if( person ) data.push(person)
    
    // then create a new one
    person = {name: val, actions: ''}
  
  // add the action to the current person (if there is one)
  }else if( person ){
    person.actions += val
  }

})

console.log(data)




答案 1 :(得分:0)

这是凯文的类似解决方案。最大的区别在于它创建新对象并将它们添加到数组中,而不是仅仅附加到现有值。希望它有所帮助!

f = open("customerInfo.txt", "r")
for line in f.readlines():
z = line.split(", ")
UserID = z[0]
CreditBalance = z[1]
MinBalance = z[2]
MaxBalance = z[3]
HowManyAwayFromMaxBalance = MaxBalance - CreditBalance

if int(z[2]) - int(z[1] <= 0:
    CreditInfo = open("creditinfo.txt", "w") #This is a blank text file
    CreditInfo.write("User", UserID, "needs more credits. In order to reach the maximum credit balance, they would need", HowManyAwayFromMaxBalance, "credits added to their account./n"

答案 2 :(得分:0)

您可以使用.match() RegExp /NAME.+(?=\s\n)/g/ACTION.+(?=\s\n)/g来匹配以"NAME""ACTION".map()开头的行,使用.replace() RegExp /^[A-Z:\s]+/替换"NAME""ACTION"":"和空格字符。

使用.length获取最大数组Math.max(),以设置for循环的最大迭代次数。 .push()数组的新对象;如果元素索引不存在于.length的数组的索引处,则将空字符串""设置为属性值。

var text = `NAME: joe 
ACTION: running 
NAME: paul 
ACTION: walking 
ACTION: swimming 
NAME: mary 
NAME: joe 
ACTION: sleeping 
NAME: paul 
NAME: mary 
NAME: ken 
ACTION: jumping 
ACTION: running 
ACTION: eating`;

var [res, ...[names, actions]] = [[]
                                 , text.match(/NAME.+(?=\s\n)/g)
                                 , text.match(/ACTION.+(?=\s\n)/g)
                                 ].map(function(arr) {
                                    return arr.map(function(value) {
                                      return value.replace(/^[A-Z:\s]+/, "")
                                    })
                                  });

for (var i = 0; i < Math.max(names.length, actions.length); i++) {
  res.push({name:names[i] || "", action: actions[i] || ""})
};

console.log(res);