简体   繁体   English

如何使用lodash.keyBy更改集合中每个项目的标识符?

[英]How can I change the identifier of each item in collection with lodash.keyBy?

I have a JSON string. 我有一个JSON字符串。

"1":{"name":"AK-47 | Aquamarine Revenge (Battle-Scarred)","price":"13.55","sold":"444"},"2":{"name":"AK-47 | Aquamarine Revenge (Factory New)","price":"38.96","sold":"157"} 

and so on... 等等...

How can I remove the numbers (1,2,3,etc...), and use the "name" value to identify each item intead? 如何删除数字(1、2、3等),并使用“名称”值标识每个项目? I've looked at lodash.keyBy, but I haven't been able to make "name" the identifier. 我看过lodash.keyBy,但无法将“名称”作为标识符。 The end goal is to be able to do call obj[itemName] - and receive the price. 最终目标是能够调用obj[itemName] -并接收价格。

Lodash has a different method _.mapKeys which suits this a little better: Lodash有另一种方法_.mapKeys ,它更适合于此:

 const obj = { "1": { "name":"AK-47 | Aquamarine Revenge (Battle-Scarred)", "price":"13.55", "sold":"444" }, "2":{ "name":"AK-47 | Aquamarine Revenge (Factory New)", "price":"38.96", "sold":"157" } } console.log(_.mapKeys(obj, (val) => val.name)); 
 <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.4/lodash.min.js"></script> 

Like this? 像这样?

x = x={"1":{"name":"AK-47 | Aquamarine Revenge (Battle-Scarred)","price":"13.55","sold":"444"},"2":{"name":"AK-47 | Aquamarine Revenge (Factory New)","price":"38.96","sold":"157"} }
_.reduce(x, (acc,o) => {acc[o.name] = o; return acc;}, {})

If you want, you can also remove the "name" from the resultant key, and also create a copy of the original instead of reference. 如果需要,还可以从结果键中删除“名称”,并创建原始副本的副本而不是引用。

_.reduce(x, (acc,o) => {acc[o.name] = Object.assign({},o); delete acc[o.name].name; return acc;}, {})

Why does it have to be done with _.keyBy ? 为什么必须使用_.keyBy完成? How about with _.each and _.omit ? _.each_.omit怎么_.omit ( _.omit makes the assumption you don't need the name key/value pair anymore) _.omit假定您不再需要name键/值对)

var before = {"1":{"name":"AK-47 | Aquamarine Revenge (Battle-Scarred)","price":"13.55","sold":"444"},"2":{"name":"AK-47 | Aquamarine Revenge (Factory New)","price":"38.96","sold":"157"}};
var after = {};

_.each(before, function(b4) {
  after[b4.name] = _.omit(b4, 'name');
});

See: https://repl.it/@dexygen/stackoverflowq48085676 参见: https : //repl.it/@dexygen/stackoverflowq48085676

This gives you the whole item by giving a specific name. 通过指定特定名称,可以为您提供整个商品。

var jsonArray = [{name: "AK-47 | Aquamarine Revenge (Factory New)", price: "38.96", sold: "157"}, {name: "Glock-18 | Fade (Factory New)", price: "287,10", sold: "256"}];

function match(x) {
return x[this[0]]===this[1];
}

var nameToCheck = "AK-47 | Aquamarine Revenge (Factory New)"

var getObject = jsonArray.filter(match, ["name", nameToCheck]);

console.log(getObject);

If you want the price, you just do: 如果您想要价格,则只需执行以下操作:

var price = getObject[0].price;

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

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