将数据复制到对象的嵌套数组中

时间:2020-05-29 04:14:11

标签: javascript arrays copy arrayobject nested-object

所以,伙计们,我不给这个话题做个话题。我无法将数据从Object数组复制到另一个新创建的数组。

例如,我想复制并创建一个新的array,其中包含数据库中每个人的所有动物类别。

 people = [ 
     {
         name: "Person 1",
         animals: [
             { category: "cat" },
             { category: "dog" },
             { category: "fish" }
         ]
     },
     {
         name: "Person 2",
         animals: [
             { category: "dog" },
             { category: "iguana" }
         ]
     },
     {
         name: "Person 3",
         animals: [
             { category: "cat" }
         ]
     }
 ]

因此,我创建了一个名为array的新animalCategory来容纳所有可用的类别。

 // declare new array to hold category of animals
 let animalCategory = []

这是我想出的逻辑:-

// loop all person available
people.forEach(person => {
    // go and loop inside animals array
    person.animals.forEach(animal => {
        // save new category of animals if animalCategory array is EMPTY
        if(animalCategory.length === 0) {
            animalCategory.push(animal.category)
        }

        // if NOT EMPTY, then
        else {
            // loop and check existing animal categories in animalCategory array
            animalCategory.forEach(category => {
                // check if MATCH?
                if(category === animal.category) {
                    break // or just continue or will NOT BE SAVE
                }

                // if NOT MATCH, then
                else {
                    // SAVE new category
                    animalCategory.push(animal.category)
                }
            })
        }
    })
})

// see result
console.log(animalCategory.length)

但是不幸的是,结果是我得到了一大堆animalCategory。还有很多重复动物类别。 (如下所示)

enter image description here

更新:我要查找的输出是:-

animalCategory: [ 'cat', 'dog', 'iguana', 'fish']

那我该如何更改我的逻辑?还有其他方法可以做到吗?

5 个答案:

答案 0 :(得分:1)

下面是一个示例,该示例将删除重复项,然后获取您要查找的输出。

people = [ 
     {
         name: "Person 1",
         animals: [
             { category: "cat" },
             { category: "dog" },
             { category: "fish" }
         ]
     },
     {
         name: "Person 2",
         animals: [
             { category: "dog" },
             { category: "iguana" }
         ]
     },
     {
         name: "Person 3",
         animals: [
             { category: "cat" }
         ]
     }
 ];
 
 const uniqAnimals = [...new Set(people.flatMap(p => p.animals).map(a => a.category))];
 
 console.log(uniqAnimals);

答案 1 :(得分:1)

people = [ 
     {
         name: "Person 1",
         animals: [
             { category: "cat" },
             { category: "dog" },
             { category: "fish" }
         ]
     },
     {
         name: "Person 2",
         animals: [
             { category: "dog" },
             { category: "iguana" }
         ]
     },
     {
         name: "Person 3",
         animals: [
             { category: "cat" }
         ]
     }
 ]

// declare new array to hold category of animals
 let animalCategory = []


// loop all person available
people.forEach(person => {
    // go and loop inside animals array
    person.animals.forEach(animal => {
        // save new category of animals if animalCategory array is EMPTY
        if(animalCategory.length === 0) {
            animalCategory.push(animal.category)
        }

        // if NOT EMPTY, then
        else {
            if(animalCategory.indexOf(animal.category) === -1) {
            
            animalCategory.push(animal.category);
            }
        }
    });
});

// see result
animalCategory.forEach(function(animal) {
    console.log(animal);
});

希望这会有所帮助。

答案 2 :(得分:0)

您可以尝试使用Set。集合仅由唯一值组成。

按下相同的值并不重要,只是不会将其添加到集合中。

如果要随后将类别转换回数组,请使用Array.from方法并传入集合。

let animalCategory = new Set()
people.forEach(person => {
    // go and loop inside animals array
    person.animals.forEach(animal => {
          animalCategory.add(animal.category)
    })
})
animalCategory = Array.from(animalCategory)

答案 3 :(得分:0)

这是另一种解决方案。

AggregationCursor {


 _readableState: ReadableState {
    objectMode: true,
    highWaterMark: 16,
    buffer: BufferList { head: null, tail: null, length: 0 },
    length: 0,
    pipes: null,
    pipesCount: 0,
    flowing: null,
    ended: false,
    endEmitted: false,
    reading: false,
    sync: true,
    needReadable: false,
    emittedReadable: false,
    readableListening: false,
    resumeScheduled: false,
    emitClose: true,
    autoDestroy: false,
    destroyed: false,
    defaultEncoding: 'utf8',
    awaitDrain: 0,
    readingMore: false,
    decoder: null,
    encoding: null,
    [Symbol(kPaused)]: null
  },
  readable: true,
  _events: [Object: null prototype] {},
  _eventsCount: 0,
  _maxListeners: undefined,
  operation: AggregateOperation {
    options: { readPreference: [ReadPreference] },
    ns: MongoDBNamespace { db: 'alumni-portal', collection: '$cmd' },
    readPreference: ReadPreference { mode: 'primary', tags: undefined },
    readConcern: undefined,
    writeConcern: undefined,
    explain: false,
    fullResponse: true,
    target: 'posts',
    pipeline: [ [Object] ],
    hasWriteStage: false,
    cursorState: {
      cursorId: null,
      cmd: {},
      documents: [],
      cursorIndex: 0,
      dead: false,
      killed: false,
      init: false,
      notified: false,
      limit: 0,
      skip: 0,
      batchSize: 1000,
      currentLimit: 0,
      transforms: undefined,
      raw: undefined
    }
  },
  pool: null,
  server: null,
  disconnectHandler: undefined,
  bson: BSON {},
  ns: 'alumni-portal.$cmd',
  namespace: MongoDBNamespace { db: 'alumni-portal', collection: '$cmd' },
  cmd: {},
  options: {
    readPreference: ReadPreference { mode: 'primary', tags: undefined }
  },
  topology: NativeTopology {
    _events: [Object: null prototype] {
      authenticated: [Function],
      error: [Array],
      timeout: [Array],
      close: [Array],
      parseError: [Array],
      fullsetup: [Array],
      all: [Array],
      reconnect: [Array],
      commandStarted: [Function],
      commandSucceeded: [Function],
      commandFailed: [Function],
      serverOpening: [Function],
      serverClosed: [Function],
      serverDescriptionChanged: [Function],
      serverHeartbeatStarted: [Function],
      serverHeartbeatSucceeded: [Function],
      serverHeartbeatFailed: [Function],
      topologyOpening: [Function],
      topologyClosed: [Function],
      topologyDescriptionChanged: [Function],
      joined: [Function],
      left: [Function],
      ping: [Function],
      ha: [Function],
      connectionPoolCreated: [Function],
      connectionPoolClosed: [Function],
      connectionCreated: [Function],
      connectionReady: [Function],
      connectionClosed: [Function],
      connectionCheckOutStarted: [Function],
      connectionCheckOutFailed: [Function],
      connectionCheckedOut: [Function],
      connectionCheckedIn: [Function],
      connectionPoolCleared: [Function],
      open: [Function]
    },
    _eventsCount: 35,
    _maxListeners: Infinity,
    s: {
      id: 0,
      options: [Object],
      seedlist: [Array],
      state: 'connected',
      description: [TopologyDescription],
      serverSelectionTimeoutMS: 30000,
      heartbeatFrequencyMS: 10000,
      minHeartbeatFrequencyMS: 500,
      Cursor: [Function: Cursor],
      bson: BSON {},
      servers: [Map],
      sessionPool: [ServerSessionPool],
      sessions: Set {},
      promiseLibrary: [Function: Promise],
      credentials: [MongoCredentials],
      clusterTime: [Object],
      connectionTimers: Set {},
      sCapabilities: [ServerCapabilities]
    },
    [Symbol(kCapture)]: false,
    [Symbol(waitQueue)]: Denque { _head: 3, _tail: 3, _capacityMask: 3, _list: [Array] }
  },
  cursorState: {
    cursorId: null,
    cmd: {},
    documents: [],
    cursorIndex: 0,
    dead: false,
    killed: false,
    init: false,
    notified: false,
    limit: 0,
    skip: 0,
    batchSize: 1000,
    currentLimit: 0,
    transforms: undefined,
    raw: undefined
  },
  logger: Logger { className: 'Cursor' },
  s: {
    numberOfRetries: 5,
    tailableRetryInterval: 500,
    currentNumberOfRetries: 5,
    state: 0,
    promiseLibrary: [Function: Promise],
    explicitlyIgnoreSession: false
  },
  [Symbol(kCapture)]: false
}

答案 4 :(得分:0)

我们可以收集数组中的所有类别属性值,并从中删除重复的值。

var people = [{
    name: "Person 1",
    animals: [{
        category: "cat"
      },
      {
        category: "dog"
      },
      {
        category: "fish"
      }
    ]
  },
  {
    name: "Person 2",
    animals: [{
        category: "dog"
      },
      {
        category: "iguana"
      }
    ]
  },
  {
    name: "Person 3",
    animals: [{
      category: "cat"
    }]
  }
];
var getArr = [];
var animalsArr = people.map(x => x.animals.map(y => {
  getArr.push(y.category);
}));

var filteredArr = getArr.filter((value, index, self) => self.indexOf(value) === index);
console.log(filteredArr);
相关问题