【问题标题】:Changing an array to an object将数组更改为对象
【发布时间】:2016-03-29 16:31:04
【问题描述】:

我的问题是可以改变和排列成一个对象吗?

以下代码计算数组中每个单词的出现次数。

// function for getting the frequency of each word within a string
function getFreqword(){
  var string = tweettxt.toString(), // turn the array into a string
      changedString = string.replace(/,/g, " "), // remove the array elements 
      split = changedString.split(" "), // split the string 
      words = []; 

  for (var i=0; i<split.length; i++){
    if(words[split[i]]===undefined){
      words[split[i]]=1;
    } else {
      words[split[i]]++;
    }
  }
  return words;
}

是否可以改变它,而不是像这样返回一个数组:

[ Not: 1,
  long: 1,
  left: 2,
  grab: 1,
  an: 4,
  Easter: 5,
  bargain: 1,]

而是返回一个像这样的对象? { word: 'Not' num: 1 }

【问题讨论】:

  • 您可以使用括号表示法分配对象属性。 var obj = {}; 然后点符号添加属性 obj.prop1 = 2; 或括号符号,如 obj["prop2"] = 2; 方便的是括号符号可以使用字符串,因此 var propName = "prop3" 然后 obj[propName] = 2;obj.prop3 === 2 设为 true。
  • 我想你真正想要的是一个对象数组:[ { word: 'Not', num: 1 }, { word: 'long', num: 1 }, ... ] 而不是而不是单个对象。
  • @Andy tweetext is and array that then变成一个可以排序的字符串
  • @Arnauld 如果我可以按对象的 num 元素对该数组进行排序,那么可以。
  • @cockmagic,你能显示初始tweetxt 值吗?

标签: javascript arrays object javascript-objects


【解决方案1】:

您可以使用Object.key()Array#map() 将对象转换为对象数组。

var obj = { Not: 1, long: 1, left: 2, grab: 1, an: 4, Easter: 5, bargain: 1 },
    array = Object.keys(obj).map(function (k) { return { word: k, num: obj[k] }; });

document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');

// edit sorting

array.sort(function (a, b) { return a.num - b.num; });
document.write('<pre>' + JSON.stringify(array, 0, 4) + '</pre>');

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-02
    • 2014-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    • 2021-12-02
    相关资源
    最近更新 更多