【问题标题】:Create an array of array's of object from Nested Objects从嵌套对象创建一个对象数组
【发布时间】:2020-12-21 11:46:12
【问题描述】:

假设我们有一个包含对象数组的数组

let array = [
[{value:'a',somepros:"old"}],
[{value:'d',somepros:"old"}],
[{value:'b',somepros:"old"}]
];

我们有类似嵌套的Obj

let obj ={
"a":{
"count":2
},
"b":{
"count":2
},
"c":{
"count":1
},
"e":{
"count":1
}
};

现在我想要的基本上是使用嵌套对象我想检查对象的数组值的数组是否存在,并想创建一个如上所述的数组。这里对象中的计数是对象数组将出现在上述数组中的次数。假设对象属性“a”的计数为 2,已经存在一个具有值“a”的对象数组。我希望另一个数组被推送的次数是计数但已经存在 1 所以我会再添加 1 次。 我需要的是来自 Obj:

NewArr =[
[{value:'a',somepros:"old"}],
[{value:'a',somepros:"newpushed"}],
[{value:'b',somepros:"old"}],
[{value:'b',somepros:"newpushed"}],
[{value:'c',somepros:"newpushed"}],
[{value:'e',somepros:"newpushed"}],
];

【问题讨论】:

    标签: javascript arrays object multidimensional-array


    【解决方案1】:

    在我看来,这个问题似乎没有多大意义,但它是:

    let array = [
      [{value:'a',somepros:"old"}],
      [{value:'d',somepros:"old"}],
      [{value:'b',somepros:"old"}]
    ],
    obj ={
      "a":{
        "count":2
      },
      "b":{
        "count":2
      },
      "c":{
        "count":1
      },
      "e":{
        "count":1
      }
    };
    
    const res = [];
    // loop each entry from obj.
    for (const [key, {count}] of Object.entries(obj)) {
      // check whether the key exists in the original array.
        const matched = array.find((arr) => arr[0].value === key);
      // If it exists, push it.
      if (matched) res.push(matched);
      // then, add X elements "newpushed", where X is given by the count declared - 0 if matched doesn't exist, otherwise 1 (since an element already existed).
      res.push(
        ...Array.from({length: (count - (matched ? 1 : 0))}, (_) => ([{ value: key, somepros: 'newpushed' }]))
      );
    }
    
    console.log(res);

    sn-p 中的注释解释了所做的工作。

    【讨论】:

    • 我发现您的回答非常有用。但是我仍然有一个问题,因为我正在使用数据表,它需要对象格式的数组数组中的数据,我已经解释过了。问题仍然存在如果前面的我的意思是旧数组有数据``` [ [{value:'a',somepros:"old"}], [{value:'a',somepros:"old2"}], [{value:'d',somepros:"old"}], [{value:'b',somepros:"old"}] ], ```那么解决这个问题的方法是什么?
    猜你喜欢
    • 2019-10-06
    • 1970-01-01
    • 2022-11-03
    • 2022-11-25
    • 2021-06-07
    • 2022-01-18
    • 2021-11-28
    • 2021-08-02
    • 1970-01-01
    相关资源
    最近更新 更多