使用javascript中的另一个对象的值创建新对象

时间:2016-05-21 05:47:51

标签: javascript arrays

我们如何使用JavaScript更改以下数据对象的结构。需要对标准下的所有名称进行分类。提前致谢

[
    {
        "name": "Rohan",
        "std": "3"
    },
    {
        "name": "Jack",
        "std": "2"
    },
    {
        "name": "Peter",
        "std": "2"
    }
]

[
    {
        "std": "2",
        "details": [
            {
                "name": "Jack"
            },
            {
                "name": "Peter"
            }
        ]
    },
    {
        "std": "3",
        "details": [
            {
                "name": "Rohan"
            }
        ]
    }
]

4 个答案:

答案 0 :(得分:1)

您可以在此处使用 reduce() 方法

var data = [{
    "name": "Rohan",
    "std": "3"
  }, {
    "name": "Jack",
    "std": "2"
  }, {
    "name": "Peter",
    "std": "2"
  }],
  res = [],
  kmap = {};

res = data.reduce(function(a, b) {
  // check std value already in array using kmap object
  if (kmap[b.std]) {
    //  if already exist then push name attribute in the details 
    a[kmap[b.std] - 1].details.push({
      'name': b.name
    });
  } else {
    // in else case push the new object 
    a.push({
      'std': b.std,
      'details': [{
        'name': b.name
      }]
    });
    kmap[b.std] = a.length; // storing the (index + 1) value to avoid 0 in if condition
  }
  return a;
}, []);

console.log(res);

对于旧版浏览器,请检查polyfill option for reduce method

答案 1 :(得分:1)

使用Array.forEachArray.mapObject.keys函数的解决方案:

var arr = [{"name": "Rohan", "std": "3"}, { "name": "Jack", "std": "2" }, { "name": "Peter", "std": "2" }],
    grouped = {}, result;

arr.forEach(function(obj){
    var std = obj['std'];
    if (this[std]) {
        this[std]['details'].push({'name' : obj['name']});
    } else {
        this[std] = {'std' : std, 'details' : [{'name' : obj['name']}]};
    }
}, grouped);
result = Object.keys(grouped).map((k) => grouped[k]);

console.log(JSON.stringify(result, 0, 4));

输出:

[
    {
        "std": "2",
        "details": [
            {
                "name": "Jack"
            },
            {
                "name": "Peter"
            }
        ]
    },
    {
        "std": "3",
        "details": [
            {
                "name": "Rohan"
            }
        ]
    }
]

答案 2 :(得分:0)

这样的问题是递归的好选择。这是一种可能的递归解决方案。您可以使用underscore.js等函数式编程框架使其更漂亮。



var objs = [
{
    "name": "Rohan",
    "std": "3"
},
{
    "name": "Jack",
    "std": "2"
},
{
    "name": "Peter",
    "std": "2"
}
];

function categorize(objs) {
    if (objs.length === 0) {
        return [];
    } else {
        var first = objs.shift();
        var categorized = categorize(objs);
        for(var i = 0; i < categorized.length; i++) {
            if (categorized[i].std === first.std) {
                categorized[i].details.push({name: first.name});
                break;
            }
        }
        if(i === categorized.length) {
             categorized.push({std: first.std, details: [{name: first.name}]});
        }
        return categorized;
    }
}

var res = categorize(objs);
console.log(res);
&#13;
&#13;
&#13;

答案 3 :(得分:0)

如果你正在使用lodash(我知道这个问题没有问过这个问题会慢一些,但它可能对某人有用:))

var data = [
  { "name": "Rohan", "std": "3" },
  { "name": "Jack", "std": "2" },
  { "name": "Peter", "std": "2" }
];

var grouped = _.chain(data)
  .groupBy('std')
  .map(function (people, std) {
    return {
      std: std,
      details: _.map(people, function(person) {
        return { name: person.name };
      })
    }
  }).value();