简体   繁体   中英

return a new object with keys from array

I am trying to create a new object from the people array below, using born as a key, that contains all the people born in that year:

 const newObject = {
      '1971': {
        male: [ [Object], [Object] ],
        female: [ [Object] ]
      },
      '1972': {
        male: [ [Object], [Object] ],
        female: [ [Object] ]
      }
    }

Here is my code so far:

people.map(person => {
  let {
    born,
    sex
  } = person;

  newPeople[born] = sex == "male" ? {
    male: Array.isArray(male) && array.length ? male.push(person) : [],
    female: Array.isArray(female) && female.length ? female.push(person) : []}
})

Array of people:

const people = [{
    name: 'Jim',
    sex: 'male',
    born: '1971',
    address: {
      town: 'London',
    },
  },
  {
    name: 'Bob',
    sex: 'male',
    born: '1971',
    address: {
      town: 'London',
    },
  },....

jsfiddle setup here: https://jsfiddle.net/jw9n3bmr/

Here is a solution with reduce for what you want to do:

 const people = [{ name: 'Jim', sex: 'male', born: '1971', address: { town: 'London', }, }, { name: 'Bob', sex: 'male', born: '1971', address: { town: 'London', }, } ]; const result = people.reduce((acc, currVal) => { (acc[currVal.born] || (acc[currVal.born] = { male: [], female: [] }))[currVal.sex].push(currVal); return acc; }, {}); console.log(result);

I hope this could helps.

const getItems = (array, key, value) => {
    let items = [];
    array.forEach((k, o) => { if (o[key] === value) items.push(o) });
    return items;
};

console.log(getItems(people, "born", "1971"));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM