JS映射两个对象/数组

时间:2017-04-09 17:41:01

标签: javascript

我有2个格式的对象:

obj1 = [
          {
            "code": "in_today",
            "text": "Today"
          },
          {
            "code": "in_week",
            "text": "This week"
          },
          {
            "code": "in_month",
            "text": "This month"
          },
          {
            "code": "normal",
            "text": "Other"
          }
        ]

obj2 store" code"在obj1中定义的值:

obj2 = ["in_today", "in_week", "normal"]

如何使用obj2的值将obj1更改为类似的内容:

[
    {
        "code": "in_today",
        "text": "Today",
        "selected": true
    },
    {
        "code": "in_week",
        "text": "This week",
        "selected": true
    },
    {
        "code": "in_month",
        "text": "This month",
        "selected": false
    },
    {
        "code": "normal",
        "text": "Other"
        "selected": true
    }
]

这个案例的最佳解决方案是什么? 谢谢!

4 个答案:

答案 0 :(得分:1)

您可以使用acc根据Array.map是否在code数组中来转换对象:

obj2

如果ES6可用,或者更简单一点:

var obj1 = [
  {
    "code": "in_today",
    "text": "Today"
  },
  {
    "code": "in_week",
    "text": "This week"
  },
  {
    "code": "in_month",
    "text": "This month"
  },
  {
    "code": "normal",
    "text": "Other"
  }
]

var obj2 = ["in_today", "in_week", "normal"]

var newObject = obj1.map(function(obj) {
  if (obj2.indexOf(obj.code) > -1) {
    obj.selected = true;
  } else {
    obj.selected = false;
  }
  return obj;
})

console.log(newObject)

答案 1 :(得分:0)



obj1 = [
          {
            "code": "in_today",
            "text": "Today"
          },
          {
            "code": "in_week",
            "text": "This week"
          },
          {
            "code": "in_month",
            "text": "This month"
          },
          {
            "code": "normal",
            "text": "Other"
          }
        ]

obj2 = ["in_today", "in_week", "normal"];
    
    obj1.forEach( function(elem){

     if( obj2.indexOf(elem.code) > -1)
       elem.selected = true;
     else
       elem.selected = false;

    });
    
    console.log( JSON.stringify(obj1) );




答案 2 :(得分:0)

使用Array#forEach简单快捷的解决方案。

var obj1 = [{"code":"in_today","text":"Today"},{"code":"in_week","text":"This week"},{"code":"in_month","text":"This month"},{"code":"normal","text":"Other"}],
    obj2 = ["in_today", "in_week", "normal"];

    obj1.forEach(v => v.selected = obj2.indexOf(v.code) > -1);

    console.log(obj1);

答案 3 :(得分:0)

你想要做这样的事情:

for (var i = 0; i < obj1.length; ++i) {
  if (obj2.indexOf(obj1[i].code) == -1) {
    obj1[i].selected = false;
  } else {
    obj1[i].selected = true;
  }
}

基本上,你只需循环遍历obj1,然后检查obj2中是否存在obj1.code的值,然后相应地设置selected