向对象数组添加新属性(根据现有属性值指定特定值)

时间:2015-08-10 23:33:37

标签: javascript arrays object

在一个对象数组中,如何根据特定对象的属性之一将具有特定值的新属性添加到特定对象中?值即可。让人惊讶。那是一口气。

例如,这是一个对象数组:

var data = [
    {"label":"event1","name":"Red Total","count":220,},
    {"label":"event2","name":"Green Total","count":330,},
    {"label":"event3","name":"Blue Total","count":440,},
    {"label":"overlap1","name":"Red","count":200,},
    {"label":"overlap2","name":"Green","count":300}
]

所有这些对象都应该有两个新属性:xy。我知道值为label的{​​{1}}应始终分配event1 x0.5 { {1}}。我知道值为y的{​​{1}}应始终分配0.75 labelevent2 { {1}}等等......以下是我想要的结果。

x

x和y值尚未存储在任何特定的地方或格式中,它们只是已知的,因此非常灵活。

想法1:也许它们应该作为另一个对象数组存储,并以1 / 3作为公共密钥,然后根据该键的值以某种方式合并这两个对象?我不知道。

y

想法2:或者可能将它们存储为一对数组?

0.235

更多上下文:我也不会总是知道数组中的哪些对象。有时候会var data = [ {"label":"event1","name":"Red Total","count":220,"x":0.5,"y":0.75}, {"label":"event2","name":"Green Total","count":330,"x":0.333,"y":0.235}, {"label":"event3","name":"Blue Total","count":440,"x":0.666,"y":0.235}, {"label":"overlap1","name":"Red","count":200,"x":0.9,"y":0.9}, {"label":"overlap2","name":"Green","count":300,"x":0.9,"y":0.9} ] labelvar xAndY = [ {"label":"event1","x":0.5,"y":0.75}, {"label":"event2","x":0.333,"y":0.235} } 。有时,只有var xAndY = [ [0.333,0.75], [0.666,0.235] } event1。所以,我正在考虑某种event2陈述。喜欢Idea 1(用简单的语言):

event3

或创意2

event1

显然我不知道如何处理这个问题。感谢您给我的任何指示。

2 个答案:

答案 0 :(得分:1)

离开 Idea 1 ,您可以将x和y值存储为JavaScript对象,其中对象键是数据数组中的不同标签。然后,您可以遍历数据数组(对象),并在标签存在时从x_and_ys对象中分配x和y值(请参阅下面的示例)。

var x_and_ys = {"event1": {"x": 0.5, "y": 0.75},
                "event2": {"x": 0.333, "y": 0.235}};

data.forEach(function (arrEntry, index) {
    if (x_and_ys[arrEntry["label"]] !== undefined) {
        for (var x_or_y in x_and_ys[arrEntry["label"]]) {
            arrEntry[x_or_y] = x_and_ys[arrEntry["label"]][x_or_y]; 
        }    
    }
});

另请参阅此JSFiddle:https://jsfiddle.net/v4z020fs/

答案 1 :(得分:1)

这可能是使用map的好地方(可能通过lodash或下划线):

var data = [
    {"label":"event1","name":"Red Total","count":220,},
    {"label":"event2","name":"Green Total","count":330,},
    {"label":"event3","name":"Blue Total","count":440,},
    {"label":"overlap1","name":"Red","count":200,},
    {"label":"overlap2","name":"Green","count":300}
]

var valueMap = {
  event1: {
    x: 0.5,
    y: 0.75
  },
  event2: {
    x: 1,
    y: 2
  },
  event3: {
    x: 2,
    y: 4
  },
  overlap1: {
    x: 6,
    y: 3
  },
  overlap2: {
    x: 0.3,
    y: 0.1
  }
}

var fullData = data.map(function(el) {
  var values = valueMap[el.label];
  el.x = values.x;
  el.y = values.y;
  return el;
})