简体   繁体   English

遍历对象并获取键以重新分配它们

[英]Iterate through an object and grab the keys to reassign them

I have a small snippet of code. 我有一小段代码。 This code will grab an object that has key value pairs. 此代码将获取具有键值对的对象。 I have another object that is an empty array. 我有另一个对象,它是一个空数组。 I want to iterate over the object and create arrays of each value pair in from the collection and push each array to the empty array object. 我想遍历对象,并从集合中创建每个值对的数组,然后将每个数组推入空数组对象。

What I am currently doing is passing in a collection (empty array) and a function. 我目前正在做的是传递一个集合(空数组)和一个函数。 I want to create another function that wil apply a function to each item in the object. 我想创建另一个函数,将该函数应用于对象中的每个项目。 I am able to grab each objects value and empty collection. 我能够获取每个对象的值并清空集合。 I need to grab each values key and create an array out it. 我需要抓住每个值键并为其创建一个数组。

    var letters = {d: 'dog', e: 'elephant', f: 'flotsam'};
    var iterations = [];

    _.each(letters, function(value, property) {
      iterations.push([value, property]);
    });

    expect(iterations).to.eql([
      ['dog', 'd'],
      ['elephant', 'e'],
      ['flotsam', 'f']
    ]);

// this is the function that accepts a empty collection and callback 
_.each = function(collection, iterator) {
    console.log(Object.keys(collection))
    for (var i = 0; i < collection.length; i++){
      // I want to insert the key where the (i) is located below
      iterator(collection[i],i , collection);
    };
  };

I want to grab each key when cycling through the passed collection and insert that key where the (i) is two lines from the bottom of the code snippet below. 我想在循环通过传递的集合时抓住每个键,并在(i)是下面代码段底部的两行的位置插入该键。 I tried a few different things but they are not working. 我尝试了几种不同的方法,但是它们不起作用。

Using native forEach : 使用本机forEach

_.each = function(collection, iterator) {
    Object.keys(collection).forEach(x => iterator(collection[x], x, collection));
};

If you want to get the key value pair you can use the map method on the keys of the object for example: 如果要获取键值对,则可以在对象的键上使用map方法 ,例如:

const myArray = Object.keys(letters).map((key)=>[letters[key], key])

If this is not what you want you can tell me: 如果这不是您想要的,可以告诉我:

isn't only this is enough 不仅够了

_.map(letters, (v,k)=>[v,k])

Remember, you can use all the underscore/lodash collection functions on object directly with value/key pairs. 请记住,您可以直接在对象上使用所有underscore/lodash集合函数和value/key对。

 var letters = {d: 'dog', e: 'elephant', f: 'flotsam'}, iterations = _.map(letters, (v,k)=>[v,k]); console.log('Iterations: ', iterations); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.9.1/underscore-min.js"></script> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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