从另一个数组的值派生一个数组

时间:2016-05-23 18:55:46

标签: javascript typescript

我将这个产品数组放在一个有角度的2分量中:

products = [{name: "product1", product_properties: [{name: "color", value: "blue"}, {name: "size", value: "small"}]}, 
            {name: "product2", product_properties: [{name: "color", value: "yellow"}, {name: "size", value: "medium"]}, 
            {name: "product3", product_properties: [{name: "color", value: "green"}, {name: "size", value: "large"}, 
            {name: "product4", product_properties: [{name: "color", value: "green"}, {name: "size", value: "small"}]} 
            {name: "product5", product_properties: [{name: "color", value: "yellow"}, {name: "size", value: "medium"}]

循环遍历此数组并使用typescript或javascript派生类似下面的数组的最有效方法是什么:

derivedArray = [{property_name: "color", values: ["blue", "yellow", "green"]}, 
                {property_name: "size", values: ["small", "medium", "large"]}] 

2 个答案:

答案 0 :(得分:2)

你的数组有一些语法错误,我修复了它们:

var inData = [
  {name: "product1", product_properties:[{name: "color", value: "blue"}, {name: "size", value: "small"} ]}, 
  {name: "product2", product_properties:[{name: "color", value: "yellow"}, {name: "size", value: "medium"}]}, 
  {name: "product3", product_properties:[{name: "color", value: "green"},  {name: "size", value: "large"}]}
];

让我们构建property => values

的哈希映射
var hash = inData.reduce((acc, p) => {
  p.product_properties.forEach(prop => {
    if (!acc[prop.name]) acc[prop.name] = [];
    if (!~acc[prop.name].indexOf(prop.value)) // filter duplicates
      acc[prop.name].push(prop.value);});
    return acc;
}, {});

现在构建请求的数据结构:

Object.keys(hash).map(key => ({property_name: key, values: hash[key]}))

结果是:

[
  {"property_name":"color","values":["blue","yellow","green"]},     
  {"property_name":"size","values":["small","medium","large"]}
]

答案 1 :(得分:0)

使用jQuery



var products = [{name: "product1", product_properties: [{name: "color", value: "blue"}, {name: "size", value: "small"}]}, 
            {name: "product2", product_properties: [{name: "color", value: "yellow"}, {name: "size", value: "medium"}]}, 
            {name: "product3", product_properties: [{name: "color", value: "green"}, {name: "size", value: "large"}]}];
var colorArray = [];
var sizeArray = [];
$.each(products,function(i,v){
var colorAttributes = v.product_properties[0];
var sizeAttributes = v.product_properties[1];
// check if attribute is already passed in the array using jQuery.inArray()
if(colorAttributes.name=="color" && $.inArray(colorAttributes.value,colorArray)==-1){
colorArray.push(colorAttributes.value);
}
if(sizeAttributes.name=="size" && $.inArray(sizeAttributes.value,sizeArray)==-1){
sizeArray.push(sizeAttributes.value);
}
});
var derivedArray = [{property_name: "color", values: colorArray}, 
                {property_name: "size", values: sizeArray}] ;
alert(JSON.stringify(derivedArray ));

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;