indexBy在lodash /下划线的对面?

问题描述 投票:2回答:3

我有一个带键的对象

 var obj = { a: { fruit: 'Apple' }, b: { fruit: 'Banana' } }

我想快速将键(a / b)移到作为属性name的值。我可以找出一个quicker way来做。

 _(obj).keys().each(function(key)
 {
     obj[key].name = key;
 })
 var results = _.values(obj);

这不完全是出于美学原因,我不能使用function关键字,因为它是一个角度表达式

underscore.js lodash
3个回答
3
投票

对于有兴趣的人,这就是我最终这样做的方式:

_.mixin({
    toArrayFromObj: function (object, keyName)
    {
        return _(object).keys().map(function (item)
        {
            object[item][keyName] = item;
            return object[item];
        }).value();
    }
});

我会很乐意采用名称或实施建议。


2
投票

我想出了一个稍微不同的解决方案:

_.mixin({
  disorder: function(collection, path) {
    return _.transform(collection, function(result, item, key) {
      if (path)
        _.set(item, path, key);

      result.push(item);
    }, []);
  }
});

由于_.set的使用,键属性也可以转移到嵌套属性。

var indexedBooks = { 
  'a1': { title: 'foo' }, 
  'a2': { title: 'bar' }
};

var books = _.disorder(indexedBooks, 'author._id');
// → [{ 'title': 'foo', 'author': { '_id': 'a1' }},
//    { 'title': 'bar', 'author': { '_id': 'a2' }}]

0
投票

这是我在打字稿中反转lodash的keyBy的版本。

import { List, Dictionary } from 'lodash';

function unkeyBy<T>(object: Dictionary<T>, key = 'id'): List<T> {
  return Object.keys(object).map((item) => {
    return { [key]: item, ...object[item] };
  });
}
© www.soinside.com 2019 - 2024. All rights reserved.