更改数组的属性

时间:2018-08-16 12:21:37

标签: javascript

有一个包含对象和数字属性的数组。

   var fruitNames = [];


   var fruit = [{"fruit": 1},{"fruit": 0},{"fruit": 3},
               {"fruit": 2},{"fruit": 1},{"fruit": 1},
               {"fruit": 2},{"fruit": 2},{"fruit": 1}];

如何将数字转换为名称,例如0 =梨,1 =香蕉,2 =苹果,3 =橙色,然后将它们放入fruitNames数组中,并根据字符串中的number属性将它们的名称作为字符串fruit数组?

5 个答案:

答案 0 :(得分:2)

var mapping = {"0": "Pear", "1": "Banana", "2":"Apple", "3":"Orange"};
var fruit = [{"fruit": 1},{"fruit": 0},{"fruit": 3},
               {"fruit": 2},{"fruit": 1},{"fruit": 1},
               {"fruit": 2},{"fruit": 2},{"fruit": 1}];
               
var updated = fruit.map(function(name) {
 return {'fruit':mapping[name['fruit']]}; 
});

console.log(updated);

答案 1 :(得分:0)

var fruitNames = [];
var fruit = [
  {"fruit": 1},
  {"fruit": 0},
  {"fruit": 3},
  {"fruit": 2},
  {"fruit": 1},
  {"fruit": 1},
  {"fruit": 2},
  {"fruit": 2},
  {"fruit": 1}
 ];
var matchingFruits = {
  0: "Pear",
  1: "Banana",
  2: "Apple",
  3: "Orange",
}

const output = fruit.map(function(e) {
  return {
    'fruit':matchingFruits[e['fruit']]
  }; 
});

console.log(output);

答案 2 :(得分:0)

enter image description here

基准:https://jsperf.com/change-properties-of-array/1

var arr = ['Pear', 'Banana', 'Apple', 'Orange']
var fruitNames = [];
var fruit = [{"fruit": 1},{"fruit": 0},{"fruit": 3},
               {"fruit": 2},{"fruit": 1},{"fruit": 1},
               {"fruit": 2},{"fruit": 2},{"fruit": 1}];
               
for (let obj of fruit) {
  fruitNames.push(arr[obj.fruit])
}

console.log(fruitNames)

var arr = ['Pear', 'Banana', 'Apple', 'Orange']
var fruitNames = [];
var fruit = [{"fruit": 1},{"fruit": 0},{"fruit": 3},
               {"fruit": 2},{"fruit": 1},{"fruit": 1},
               {"fruit": 2},{"fruit": 2},{"fruit": 1}];
               
for (let obj of fruit) {
  fruitNames.push({'fruit': arr[obj.fruit]})
}

console.log(fruitNames)
         

答案 3 :(得分:0)

var fruitNames = [];


var fruit = [{"fruit": 1},{"fruit": 0},{"fruit": 3},
            {"fruit": 2},{"fruit": 1},{"fruit": 1},
            {"fruit": 2},{"fruit": 2},{"fruit": 1}];

result = fruit.map(elm => {
  name = Object.keys(elm)[0];
  return { [elm[name]]: name };
});
console.log(result);

答案 4 :(得分:0)

var fruitNames = ["Pear", "Banana", "Apple", "Orange"];
var fruit = [{"fruit": 1},{"fruit": 0},{"fruit": 3},
             {"fruit": 2},{"fruit": 1},{"fruit": 1},
             {"fruit": 2},{"fruit": 2},{"fruit": 1}];
fruit.forEach(function(item) {
  item["fruit"] = fruitNames[item["fruit"]]
});