将员工数组转换为字典

因此,我正在使用LinqJS库来实现以下目标:

    var allEmployees = [
        {
            "Id": 1374,"FirstName": "John","LastName": "Doe"
        },{
            "Id": 1375,"FirstName": "Jane","LastName": "Doe"
        }
    ];
    var employeeDictionary = Enumerable.from(allEmployees).toDictionary("$.Id","$.FirstName+' '+$.LastName").toEnumerable().toArray();

employeeDictionary序列化为JSON时,我得到以下格式:

[
  {
    "key": 1374,"value": "John Doe"
  },{
    "key": 1375,"value": "Jane Doe"
  }
]

我不想使用这种格式的数据,我希望使用这种格式:

{
  "1374": "John Doe","1375": "Jane Doe"
}

我使用YaLinqo在PHP中写了类似的东西,这给了我所需的结果:

echo json_encode(from($employees)->toDictionary('$v["Id"]','$v["FirstName"]." ".$v["LastName"]')->toArray());

但是,我希望能够在我的JavaScript中实现这一目标。

wuzhaohai000 回答:将员工数组转换为字典

您可以使用reduce来实现:

employeeDictionary.reduce((acc,employee) => {
  acc[employee.key] = employee.value;
  return acc
},{})

或者使用对象传播来缩短版本:

employeeDictionary.reduce((acc,employee) => ({
  ...acc,[employee.key]: employee.value
}),{})
,

我认为您正在将对象数组与字典混淆。我在下面列出了两个版本,以显示差异。

您要对数据进行映射,而不是减少数据。

let allEmployees = [
  { "Id": 1374,"FirstName": "John","LastName": "Doe" },{ "Id": 1375,"FirstName": "Jane","LastName": "Doe" }
];

let defaultOptions = {
  keyField: 'Id',valueFn: (emp) => `${emp['FirstName']} ${emp['LastName']}`
};

console.log('Dictionary',toDictionary(allEmployees,defaultOptions));
console.log('Pairs',toPairs(allEmployees,defaultOptions));

function toDictionary(list,options) {
  let opts = Object.assign({ keyField: 'key',valueField: 'value' },options);
  return list.reduce((dict,item) => (Object.assign(dict,{
    [item[opts.keyField]] : opts.valueFn ? opts.valueFn(item) : item[opts.valueField]
  })),{});
}

function toPairs(list,options);
  return list.map((item) => ({
    key   : item[opts.keyField],value :  opts.valueFn ? opts.valueFn(item) : item[opts.valueField]
  }));
}
.as-console-wrapper { top: 0; max-height: 100% !important; }


这是一个列表包装器类。

class ListWrapper {
  constructor(list,options) {
    this.list       = list;
    this.keyField   = options.keyField   || 'key'
    this.valueField = options.valueField || 'value'
    this.valueFn    = options.valueFn               /* optional */
  }
  toPairs() {
    return this.list.map(e=>({key:e[this.keyField],value:this.valueFn?this.valueFn(e):e[this.valueField]}));
  }
  toDictionary() {
    return this.list.reduce((d,e)=>(Object.assign(d,{[e[this.keyField]]:this.valueFn?this.valueFn(e):e[this.valueField]})),{});
  }
}

let allEmployees = [
  { "Id": 1374,"LastName": "Doe" }
];

let listWrapper = new ListWrapper(allEmployees,{
  keyField: 'Id',valueFn: (emp) => `${emp['FirstName']} ${emp['LastName']}`
});

console.log('Dictionary',listWrapper.toDictionary());
console.log('Pairs',listWrapper.toPairs());
.as-console-wrapper { top: 0; max-height: 100% !important; }

,

在JavaScript中,数组严格总是采用数字索引结构。因此,.toArray恪守这一原则。在PHP中,数组更接近JavaScript认为简单的对象。


如果使用this LINQ JavaScript library

您可以使用.toObject方法来生成具有格式的对象-您需要传递两个函数-键选择器和值选择器,以便使用正确的数据构建对象:

var allEmployees = [
    {
        "Id": 1374,"LastName": "Doe"
    },{
        "Id": 1375,"LastName": "Doe"
    }
];
var employeeDictionary = Enumerable.from(allEmployees)
  .toDictionary("$.Id","$.FirstName+' '+$.LastName")
  .toEnumerable()
  .toObject(entry => entry.key,entry => entry.value);

/* output:
{
  "1374": "John Doe","1375": "Jane Doe"
}
*/

使用解构,键/值选择器可以转换为:

.toObject(({key}) => key,({value}) => value);

如果使用this library for LINQ operations,则需要稍微更改语法:

var allEmployees = [
    {
        "Id": 1374,"LastName": "Doe"
    }
];
var employeeDictionary = Enumerable.From(allEmployees)
  .ToDictionary("$.Id","$.FirstName+' '+$.LastName")
  .ToEnumerable()
  .ToObject("$.Key","$.Value");

/* output:
{
  "1374": "John Doe","1375": "Jane Doe"
}
*/
,

简短的linq版本

var allEmployees = [{ Id: 1374,FirstName: "John",LastName: "Doe" },{ Id: 1375,FirstName: "Jane",LastName: "Doe" }],employeeDictionary = Enumerable.From(allEmployees)
        .Select("$ => { key: $.Id,value: $.FirstName + ' ' + $.LastName }")
        .ToObject("$.key","$.value");
    
console.log(employeeDictionary);
<script src="https://cdnjs.cloudflare.com/ajax/libs/linq.js/2.2.0.2/linq.js"></script>

一种具有解构和Object.fromEntries的简短方法。

var allEmployees = [{ Id: 1374,employeeDictionary = Object.fromEntries(
        allEmployees.map(({ Id,FirstName,LastName }) =>
            [Id,[FirstName,LastName].join(' ')])
    );
    
console.log(employeeDictionary);

本文链接:https://www.f2er.com/3157761.html

大家都在问