簡體   English   中英

從數組返回一個帶有鍵的新對象

[英]return a new object with keys from array

我正在嘗試從下面的people數組中創建一個新對象,使用born作為鍵,其中包含該年出生的所有人員:

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

到目前為止,這是我的代碼:

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) : []}
})

人群:

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

jsfiddle 設置在這里: https ://jsfiddle.net/jw9n3bmr/

以下是針對您想要執行的操作使用reduce的解決方案:

 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);

我希望這會有所幫助。

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"));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM