我有一个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"}
依旧......
如何删除数字(1,2,3等等),并使用“name”值来标识每个项目的内容?
我看过lodash.keyBy,但我无法将“name”作为标识符。最终目标是能够拨打obj[itemName]
- 并收到价格。
答案 0 :(得分:2)
Lodash有一种不同的方法ERROR Error: Cannot find control with path: 'tasks -> 0 -> Roles -> 0 -> Role'
,它更适合这种方式:
_.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));

答案 1 :(得分:0)
喜欢这个?
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;}, {})
如果需要,您还可以删除"名称"从结果键中,还创建原始的副本而不是引用。
_.reduce(x, (acc,o) => {acc[o.name] = Object.assign({},o); delete acc[o.name].name; return acc;}, {})
答案 2 :(得分:0)
为什么必须使用_.keyBy
?使用_.each
和_.omit
怎么样? (_.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');
});
答案 3 :(得分:-2)
这通过给出特定名称为您提供整个项目。
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);
如果您想要价格,只需:
var price = getObject[0].price;