如何将两个集合合二为一?

时间:2017-12-29 23:24:16

标签: javascript

我在一个数组中有多个集合(如2个集合,但可能更多),如下所示:

var attributes = [ { colors: [ 10, 20, 30 ] }, { dimensions: [ a, b] } ]

我希望有这样的事情:

var newArray =  [ {10 : a },{ 10 : b },{20 : a},{20 : b},{30 : a},{30 : b} ]

2 个答案:

答案 0 :(得分:1)

如果外部数组中有两个以上的项目,我认为我不明白你想拥有什么,但这里是你的例子的解决方案:

var attributes = [{
  colors: [10, 20, 30]
}, {
  dimensions: ["a", "b"]
}];
var newArray = [];
attributes[0].colors.forEach(color => {
  attributes[1].dimensions.forEach(dim => {
    var obj = {};
    obj[`${color}`] = dim;
    newArray.push(obj);
  });
});
console.log(newArray);

  

NewToJS的其他更改 - dimensions: [a, b] dimensions: ["a", "b"]

如果你更准确地指定你想要的东西,我会尝试编辑答案,因为这完全取决于细节。

答案 1 :(得分:0)

绝对取决于。但是,如果attribute数据始终按照您的描述进行结构化,那么这就行了。

    var attributes = [ { colors: [ 10, 20, 30 ] }, { dimensions: [ "a","b"] } ]

    function crossReference(attributes, key, scope){
        let result = [];
        let variables = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"]
        if(!key && key !== 0){ 
            attributes.forEach((attr, key)=>{
                let keys = Object.keys(attr);
                keys.forEach((property)=>{
                    if(Array.isArray(attr[property])){
                        console.log(property);
                        result= result.concat(crossReference(attr[property], key, attributes));
                        // section.forEach()
                    }
                })

            })
        }else{
            console.log(attributes, scope[key+1], key);
            attributes.forEach((attr,index)=>{
                if(!scope[key+1]) return;
                let next = scope[key+1];
                let keys = Object.keys(scope[key+1]);
                keys.forEach((property)=>{
                    if(Array.isArray(next[property])){
                        next[property].forEach((prop)=>{
                            result.push({[attr]:prop})
                        })


                    }
                })

            })
        }
        return result;
    }

    console.log(crossReference(attributes))