Jestem nowy w JS. Mam listę obiektów, która wygląda jak poniżej,

var a = [
  {
    wa_id: 1,
    wa_property_id: 'p1',
    wa_view_name: 'ram'
  },
  {
    wa_id: 1,
    wa_property_id: 'p1',
    wa_view_name: 'sam'
  },
  {
    wa_id: 1,
    wa_property_id: 'p2',
    wa_view_name: 'kam'
  },
  {
    wa_id: 2,
    wa_property_id: 'p5',
    wa_view_name: 'pri'
  },
   {
    wa_id: 1,
    wa_property_id: 'p3',
    wa_view_name: 'ste',
  },
]

Chcę powtórzyć te obiekty i utworzyć nowy oddzielny obiekt. Chcę uzyskać wymagane wyjście, jak poniżej

Wymagane wyjście:

  {
        "1": {
            "p1": ["ram", "sam"],
            "p2": ["kam"],
            "p3": ["ste"]
        },
        "2": {
            "p5": ["pri"]
        }
    }

Oto kod, który wypróbowałem,

var a = [{
    wa_id: 1,
    wa_property_id: 'p1',
    wa_view_name: 'ram'
  },
  {
    wa_id: 1,
    wa_property_id: 'p1',
    wa_view_name: 'sam'
  },
  {
    wa_id: 1,
    wa_property_id: 'p2',
    wa_view_name: 'kam'
  },
  {
    wa_id: 2,
    wa_property_id: 'p5',
    wa_view_name: 'pri'
  },
  {
    wa_id: 1,
    wa_property_id: 'p3',
    wa_view_name: 'ste',
  },

]
temp_obj = {}
temp_list = []
for (var j = 0; j < a.length; j++) {
  temp_list.push(a[j].wa_property_id)
}
temp_list.splice(0, temp_list.length, ...(new Set(temp_list)))
// Property ID List
console.log(temp_list)
// Output: ["p1","p2","p5","p3"]

properyViewObj = {}
temp_list2 = []
for (var j = 0; j < temp_list.length; j++) {
  for (var k = 0; k < a.length; k++) {
    if (a[k].wa_property_id == temp_list[j]) {
      temp_list2.push(a[k].wa_view_name)
    }
  }
  properyViewObj[temp_list[j]] = temp_list2
  temp_list2 = []
}
// Property with Viewnames
console.log(properyViewObj)
// Output: {p1: ["ram","sam"],p2: ["kam"],p5: ["pri"],p3: ["ste"]}

var wa_list = []
for (var j = 0; j < a.length; j++) {
  wa_list.push(a[j].wa_id)
}
wa_list.splice(0, wa_list.length, ...(new Set(wa_list)))
// Wa_id List
console.log(wa_list)
// Output: [1,2]
// How to make the Next Step
var output = {}
var tem = []
for (var j = 0; j < wa_list.length; j++) {
  for (var k = 0; k < a.length; k++) {
    if (a[k].wa_id == wa_list[j]) {
      console.log(a[k].wa_property_id)

    }
  }
}
5
Stack Kiddy 2 kwiecień 2020, 14:35

4 odpowiedzi

Najlepsza odpowiedź

Możesz spróbować zredukować swoją tablicę do obiektu

var a = [
  {
    wa_id: 1,
    wa_property_id: 'p1',
    wa_view_name: 'ram'
  },
  {
    wa_id: 1,
    wa_property_id: 'p1',
    wa_view_name: 'sam'
  },
  {
    wa_id: 1,
    wa_property_id: 'p2',
    wa_view_name: 'kam'
  },
  {
    wa_id: 2,
    wa_property_id: 'p5',
    wa_view_name: 'pri'
  },
   {
    wa_id: 1,
    wa_property_id: 'p3',
    wa_view_name: 'ste',
  },
]

let result = a.reduce((acc,rec) =>{

//if result object doesn't contain key for wa_id - add new id key
if(!(Object.keys(acc).includes(rec.wa_id.toString())))
{
  return {...acc, [rec.wa_id]: {[rec.wa_property_id]:[rec.wa_view_name]}}
}

//if result id object doesn't contain key for property - add new property key
if(!(Object.keys(acc[rec.wa_id]).includes(rec.wa_property_id.toString())))
{
    acc[rec.wa_id] = {...acc[rec.wa_id],[rec.wa_property_id]:[rec.wa_view_name] }
  return acc
}

//otherwise add new value to array of properties
acc[rec.wa_id][rec.wa_property_id] = [...acc[rec.wa_id][rec.wa_property_id], rec.wa_view_name]
return acc
},{})

console.log(result)
1
elvira.genkel 2 kwiecień 2020, 12:05

Możesz użyć kombinacji zmniejsz i rozstępu , aby obliczyć swój obiekt.

const data = a.reduce((lkp, obj, i) => {
  const {wa_id, wa_property_id, wa_view_name} = obj;
  return {
    ...lkp,
    [wa_id]: {
      ...lkp[wa_id],
      [wa_property_id]: [...((lkp[wa_id] || {})[wa_property_id] || []), wa_view_name]
    }
  }
}, {})

console.log (data)
<script>
  var a = [{
      wa_id: 1,
      wa_property_id: 'p1',
      wa_view_name: 'ram'
    },
    {
      wa_id: 1,
      wa_property_id: 'p1',
      wa_view_name: 'sam'
    },
    {
      wa_id: 1,
      wa_property_id: 'p2',
      wa_view_name: 'kam'
    },
    {
      wa_id: 2,
      wa_property_id: 'p5',
      wa_view_name: 'pri'
    },
    {
      wa_id: 1,
      wa_property_id: 'p3',
      wa_view_name: 'ste',
    },
  ]
</script>
3
Moritz Roessler 2 kwiecień 2020, 11:45

Możesz wziąć tablicę kluczy i zredukować wynikowy obiekt.

var array = [{ wa_id: 1, wa_property_id: 'p1', wa_view_name: 'ram' }, { wa_id: 1, wa_property_id: 'p1', wa_view_name: 'sam' }, { wa_id: 1, wa_property_id: 'p2', wa_view_name: 'kam' }, { wa_id: 2, wa_property_id: 'p5', wa_view_name: 'pri' }, { wa_id: 1, wa_property_id: 'p3', wa_view_name: 'ste' }],
    keys = ['wa_id', 'wa_property_id'],
    grouped = array.reduce((r, o) => {
        keys
            .reduce((q, k, i, { length }) =>
                q[o[k]] = q[o[k]] || (i + 1 === length ? [] : {}), r)
            .push(o.wa_view_name);
        return r;
    }, {});

console.log(grouped);
.as-console-wrapper { max-height: 100% !important; top: 0; }
1
Nina Scholz 2 kwiecień 2020, 11:46

Aby to osiągnąć, możesz użyć metody ES6

const reduceObj = arr => {
    // Map all item of the array
    return arr.reduce((acc, item) => {
        // Extract information
        const { wa_id, wa_property_id, wa_view_name } = item;
        const wa_id_string = wa_id.toString();

        // Check if the accumulator have the value of the variable wa_id_string as property
        if(acc.hasOwnProperty(wa_id_string)) {
            // Update the value of property wa_property_id if it exists or assign a new one
            acc[wa_id_string][wa_property_id] = acc[wa_id_string].hasOwnProperty(wa_property_id)
                ? [...acc[wa_id][wa_property_id], wa_view_name]
                : [wa_view_name];
        }
        else {
            // create a new property
            acc[wa_id_string] = {
                [wa_property_id]: [wa_view_name],
            }
        }
        // return the accumulator
        return acc;
    }, {});
};

const a = [
    {
        wa_id: 1,
        wa_property_id: 'p1',
        wa_view_name: 'ram'
    },
    {
        wa_id: 1,
        wa_property_id: 'p1',
        wa_view_name: 'sam'
    },
    {
        wa_id: 1,
        wa_property_id: 'p2',
        wa_view_name: 'kam'
    },
    {
        wa_id: 2,
        wa_property_id: 'p5',
        wa_view_name: 'pri'
    },
    {
        wa_id: 1,
        wa_property_id: 'p3',
        wa_view_name: 'ste',
    },
];

console.log(reduceObj(a));

Radzę również przeczytać więcej o ES6, a następnie przejść z var na let & amp; const

Więcej informacji

1
Patrissol Kenfack 2 kwiecień 2020, 12:09