[英]how to get id based on value of objects and set into another object - javascript
There are two array of objects and i want to filter two values by iterating differently to get two different id.有两个对象数组,我想通过不同的迭代来过滤两个值以获得两个不同的 id。
Here is the example这是示例
1st array : list_of_products: [ { text: "Shoes", value: 1},{text:"Clothing", value: 2},{text:"Foods", value: 3}]
2nd Array: list_of_names: [{ text: "jim" , value: 1},{text:"Sim", value: 2},{text:"Tim",value:3}]
Now, i want to get the ids by filtering out two arrays based on names like this现在,我想通过基于这样的名称过滤掉两个 arrays 来获取 ID
product_name: "Clothing", person_name:"Tim"
Then i want to store the ids like this然后我想像这样存储ID
const newIds = { product_id: 2,name_id: 3}
This i have tried:这是我试过的:
const newProduct_name = list_of_products.find(name => name.text === product_name);
const newName = list_of_names.find(name => name.text === person_name);
storing it into new object like this
const values = {product_id: newProduct_name.value ,name_id: newName.value}
How to do this by minimal use of variables and faster execution?如何通过最少的变量使用和更快的执行来做到这一点?
Creating Maps or objects using the lookup values as keys lets you iterate each of your source arrays once and then have o(1) searches rather than using find()
to iterate each array many times使用查找值作为键创建 Map 或对象可让您迭代每个源 arrays 一次,然后进行 o(1) 次搜索,而不是使用
find()
多次迭代每个数组
const products= [ { text: "Shoes", value: 1},{text:"Clothing", value: 2},{text:"Foods", value: 3}], names= [{ text: "jim", value: 1},{text:"Sim", value: 2},{text:"Tim",value:3}]; const createMap = (arr) => new Map(arr.map(o => [o.text, o.value])), prodMap = createMap(products), namesMap = createMap(names); const data = [{ product_name: "Clothing", person_name: "Tim" }]; const res = data.map(o => { return { product_id: prodMap.get(o.product_name), name_id: namesMap.get(o.person_name) }; }) console.log(res)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.