通过拆分属性为数组的对象来创建对象

时间:2019-12-18 12:30:47

标签: javascript arrays

我有一个对象数组,其属性是数组(可变长度),并且我想用组合在数组属性中的元素创建的新对象(在同一数组中)替换这些对象。 我正在使用js类的函数,这就是为什么您看到“ this”的原因。 人们建议我使用.reduce()和.map(),但我不知道如何使用它们。 这是目标:


    this.apple="apple"

    this.Array=[ 
      { names:[something1, something2...]
        fruit:this.apple
        features:[feature1,feature2,...]
      }
    ]

预期输出为:

      // (expected output):

    this.Array=[
      { names:something1,
        fruit:this.apple
        features:feature1
      },
      { names:something1,
        fruit:this.apple
        features:feature2
      },
      { names:something2,
        fruit:this.apple
        features:feature1
      },
      { names:something2,
        fruit:this.apple
        features:feature2
      },
      ...
    ]

3 个答案:

答案 0 :(得分:0)

使用flatMap可以取消数组中元素的分组。

const fruit = 'apple'

const array=[ 
  { names:['something1', 'something2'],
    fruit: fruit,
    features:['feature1','feature2']
  }
]

array.flatMap(({names,fruit,features}) => {
  names.flatMap(name => {
    features.flatMap(feature => {
      console.log(({name,fruit,feature}));
    })
  })
})

答案 1 :(得分:0)

一种可能的方法是递归地遍历所有键,并为每个键生成一个或多个对象(取决于输入是值还是数组):

function combine(obj,keys,idx,arr,proto){
  arr=arr || [];
  proto=proto || {};
  keys=keys || Object.keys(obj);
  idx=idx || 0;
  if(idx>=keys.length){
    arr.push(Object.assign({},proto));
  }
  else {
    let key=keys[idx++];
    let vals=obj[key];
    if(Array.isArray(vals))
      for(let v of vals){
        proto[key]=v;
        combine(obj,keys,idx,arr,proto);
      } else {
        proto[key]=vals;
        combine(obj,keys,idx,arr,proto);
      }
  }
  return arr;
}

let org={
  name:["something1", "something2"],
  fruit:"apple",
  feature:["feature1","feature2"],
};

console.log(...combine(org));

答案 2 :(得分:-1)

.map()将是处理此问题的最佳方法,但是由于时间有限,我很快就写了这个原因:

let apple = "apple";

let Array = [
    {
        name: ["something1", "something2"],
        fruit: this.apple,
        features: ["feature1", "feature2"]
    }
];

let somethings = [];
let features = [];

Array[0].name.forEach(item => {
    somethings.push(item);
});

Array[0].features.forEach(item => {
    features.push(item);
});

let newtest = [];
for (let index = 0; index < somethings.length; index++) {
   newtest.push({
        name: somethings[index],
        fruit: apple,
        features: features[index]
   })
}

console.log(newtest);

以上代码无需使用.map()即可满足您的要求。 简而言之:

我们从初始对象中分离出2个数组,然后通过循环然后将相同的索引添加到相同的对象来创建新的数组。不确定这是否正是您想要的。

结果如下:

[
  { name: 'something1', fruit: 'apple', features: 'feature1' },
  { name: 'something2', fruit: 'apple', features: 'feature2' }
]