将一个数组对象拆分为多个数组对象

时间:2019-12-17 21:43:56

标签: javascript arrays

我正在尝试将具有数组作为属性的数组对象拆分为多个对象,每个对象都具有上一个数组的一个元素。我在js类中工作该想法编码如下:

class Example {

  async ArraySplitter(){ 

    this.Array=[ 
      { name:something,
        features:[feature1,feature2,...]
      }]

      //Which becomes:

    this.Array=[
      { name:something,
        features:feature1
      },
      { name:something,
        features:feature2
      }''
      ...
    ]
  }
}

2 个答案:

答案 0 :(得分:0)

我们可以在原始数组上使用reduce
在reduce内部,我们将map子数组并发出所需的对象。

const arr = [{
  name: "test1",
  values: ["t1", "t2"]
},
{
  name: "test2",
  values: ["t3", "t4"]
}];

const flat = arr.reduce((a, {name, values}) => {
   a.push(
     values.map(
       value => ({ name, value })
    )
  );
  return a;
}, []).flatMap(x => x);

console.log(`Flat: ${JSON.stringify(flat)}`);

答案 1 :(得分:0)

假设您要进行1-n映射。可以通过looping或通过mapping完成。

这里有一个示例代码可以帮助您(相信它是不言自明的):

// Entity representing an element, with its own features
class Element {
  constructor(name, features) {
    this.name = name;
    this.features = features;
  }

  get featureMap() {

    // Option 1: Looping 
    const map = [];
    this.features.forEach((feature) => {
      map.push({
        name: this.name,
        feature: feature
      });
    });
    return map;

    // Option 2: Map
    return this.features.map(feature => {
      return {
        name: this.name,
        feature: feature
      }
    });
  }
}

// Test 1: Get element mapped to its features
const candleElement = new Element("Candle", ["Small", "Medium", "Large"]);
console.log(candleElement.featureMap);

// Test 2: Get element mapped to its features
const roseElement = new Element("Rose", ["Red", "Green"]);
console.log(roseElement.featureMap);