【问题标题】:How to add properties to nested object in array depending on conditions如何根据条件向数组中的嵌套对象添加属性
【发布时间】:2023-03-05 20:57:01
【问题描述】:

我又一次被困在向深度嵌套的数组中添加属性。我所拥有的是:

myArray = [
    {
      "id": "123",
      "station": {
        "id": 5,
        "name": "Teststation"
      },
      "values": [
        {
          "id": "way",
          "values": [ 339, 340, 341 ]
        },
        {
          "id": "time",
          "values": [ 1, 2, 3 ]
        },
        {
          "name": "element_1",
          "type": "line",
          "result": "nok"
        },
        {
          "name": "element_2",
          "type": "rect",
          "result": "nok"
        },
        {
          "name": "element_3",
          "type": "line",
          "result": "ok"
        }
      ]
    }
  ]

myArray 可能包含更多具有与此相同结构的对象。所以我必须循环它们。我想要实现的是: 我想向拥有名为“line”或“rect”的属性的对象添加属性并且 新属性取决于结果的值

所以新的结果应该是这样的:

myArray = [
    {
      "id": "123",
      "station": {
        "id": 5,
        "name": "Teststation"
      },
      "values": [
        {
          "id": "way",
          "values": [ 339, 340, 341 ]
        },
        {
          "id": "time",
          "values": [ 1, 2, 3 ]
        },
        {
          "name": "element_1",
          "type": "line",
          "result": "nok"
          "line": { color: 'red' }
        },
        {
          "name": "element_2",
          "type": "rect",
          "result": "nok",
          "opacity": 0.2,
          "line": { color: 'gray', width: 0 },
          "fillcolor": 'green'
        },
        {
          "name": "element_3",
          "type": "line",
          "result": "ok"
          "line": { color: 'green' }
        }
      ]
    }
  ]

到目前为止,我尝试的方法似乎都有效,直到我意识到:它返回一个数组,其中包含一个包含该对象的数组。我不明白它为什么这样做以及如何只获取一个包含对象的数组。谁能帮我解决这个问题?

  addColor(myArray) {
    return myArray.map(obj => {
      for (const prop in obj) {
        if (obj.hasOwnProperty(prop) && Array.isArray(obj[prop])) {
          for (const item in obj[prop]) {
            if (obj[prop][item].hasOwnProperty('result') && (obj[prop][item].type === 'line')) {
              obj[prop][item].result === 'nok' ? obj[prop][item].line = { color: 'red' } : obj[prop][item].line = { color: 'green' };
          } else if (obj[prop][item].hasOwnProperty('result') && (obj[prop][item].type === 'rect')) {
              obj[prop][item].opacity = 0.2;
              obj[prop][item].line = { color: 'gray', width: 0 };
              obj[prop][item].result === 'nok' ? (obj[prop][item].fillcolor = 'red') : (obj[prop][item].fillcolor = 'green');
          }
          }
        }
    }
      console.log('myArray out', myArray);
      // It doesn't return anything so far so I added
      return myArray
      // But then I do get [[{}]]

  });
  }

【问题讨论】:

  • 我已经尝试了代码,我得到了一个数组。控制台响应中是否有省略号 (...)?如果是这样,请尝试扩展它。

标签: javascript arrays object nested


【解决方案1】:

添加有效的 sn-p,对您的代码稍作改动:

var myArray = [
      {
      "id": "123",
      "station": {
        "id": 5,
        "name": "Teststation"
      },
      "values": [
        {
          "id": "way",
          "values": [ 339, 340, 341 ]
        },
        {
          "id": "time",
          "values": [ 1, 2, 3 ]
        },
        {
          "name": "element_1",
          "type": "line",
          "result": "nok"
        },
        {
          "name": "element_2",
          "type": "rect",
          "result": "nok"
        },
        {
          "name": "element_3",
          "type": "line",
          "result": "ok"
        }
      ]
    }
  ];

function addColor(myArray) {
    const x =  myArray.map(obj => {

      for (const prop in obj) {
        if (obj.hasOwnProperty(prop) && Array.isArray(obj[prop])) {
          for (const item in obj[prop]) {
            if (obj[prop][item].hasOwnProperty('result') && (obj[prop][item].type === 'line')) {
              obj[prop][item].result === 'nok' ? obj[prop][item].line = { color: 'red' } : obj[prop][item].line = { color: 'green' };
          } else if (obj[prop][item].hasOwnProperty('result') && (obj[prop][item].type === 'rect')) {
              obj[prop][item].opacity = 0.2;
              obj[prop][item].line = { color: 'gray', width: 0 };
              obj[prop][item].result === 'nok' ? (obj[prop][item].fillcolor = 'red') : (obj[prop][item].fillcolor = 'green');
          }
          }
        }
    }

    return obj; //<---- Check here
  });

  return x;
 }

 addColor(myArray);

【讨论】:

    【解决方案2】:

    const myArray = [{
      "id": "123",
      "station": {
        "id": 5,
        "name": "Teststation"
      },
      "values": [{
          "id": "way",
          "values": [339, 340, 341]
        },
        {
          "id": "time",
          "values": [1, 2, 3]
        },
        {
          "name": "element_1",
          "type": "line",
          "result": "nok"
        },
        {
          "name": "element_2",
          "type": "rect",
          "result": "nok"
        },
        {
          "name": "element_3",
          "type": "line",
          "result": "ok"
        }
      ]
    }]
    
    const modifiedArray = myArray.map(item => {
      const newItem = Object.assign({}, item);
      if (newItem.values) {
        const newItemValues = newItem.values.map(value => {
          const additionalProps = {};
    
          if (value.type === 'line') {
            additionalProps.line = {
              color: (value.result === 'ok' && 'green') || 'red'
            };
          }
    
          if (value.type === 'rect') {
            additionalProps.opacity = 0.2;
            additionalProps.line = {
              color: 'gray',
              width: 0
            };
            additionalProps.fillcolor = (value.result === 'ok' && 'green') || 'red';
          }
    
          const newValue = Object.assign({}, value, additionalProps);
          return newValue;
        });
        newItem.values = newItemValues;
      }
      return newItem;
    });
    
    console.log('original:', myArray);
    console.log('modified:', modifiedArray);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-17
      • 2013-11-07
      • 2018-12-22
      • 1970-01-01
      • 2018-07-02
      • 1970-01-01
      • 2022-11-20
      • 2019-07-11
      相关资源
      最近更新 更多