更改对象的键/值

时间:2016-06-22 19:32:36

标签: javascript

如果我有这样的结果:

treeview

我如何制作:

result =  [

    { '0': 'grade', A: 'name', b1: 'number' },
    { '1': 'grade', B: 'name', b2: 'number' },
    { '2': 'grade', C: 'name', b3: 'number' }
];

我想传递类似的等级而不是姓名和号码。

3 个答案:

答案 0 :(得分:1)

无法保证对象中键的顺序。这意味着只需获取一个键数组并循环遍历它们或通过索引访问它们将无法工作。您可以使这项工作检测数字和非数字键,如下所示:

result =  [
    { '0': 'grade', A: 'name', b1: 'number' },
    { '1': 'grade', B: 'name', b2: 'number' },
    { '2': 'grade', C: 'name', b3: 'number' }
];

result.forEach(item => {
  var keys = Object.keys(item);
  var numericKey = keys.find(key => !isNaN(key));
  var nonNumericKeys = keys.filter(key => isNaN(key));

  nonNumericKeys.forEach(nonNumKey => item[nonNumKey] = numericKey);
  delete item[numericKey];
});

答案 1 :(得分:0)

假设b3:' 1'部分是一个错字...以下应该有效。



var input =  [
  { '0': 'grade', A: 'name', b1: 'number' },
  { '1': 'grade', B: 'name', b2: 'number' },
  { '2': 'grade', C: 'name', b3: 'number' }
];

function reverseMap(obj){
  var newObj = {};
  var keys = Object.keys(obj);
  for(var i=0; i<keys.length; i++){
    var k = keys[i];
    var v = obj[k];
    newObj[v] = k;
  }
  return newObj;
}

var output = [];
for(var i=0; i<input.length; i++){
  var reverseObj = reverseMap(input[i]);
  var outputObj = {};
  var number = reverseObj.grade;
  outputObj[reverseObj.name] = number;
  outputObj[reverseObj.number] = number;
  output.push(outputObj);
}

console.log(output);
&#13;
&#13;
&#13;

答案 2 :(得分:-1)

使用ES6,您可以使用for for循环和Objects.keys来执行此任务: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/keys https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/let

let newResult = [];
for(let r of result) {
  let keys = Object.keys(r);
  let obj = {};
  for(let key of keys) {
    if(/\d/.test(key)) { var value = key; }
    else if(/\w/.test(key)) { var key1 = key; }
    else if(/\d/.test(key)) { var key2 = key; }
  }

  obj[key1] = value;
  obj[key2] = value;
  newResult.push(obj);
}
return newResult;