Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
171 views
in Technique[技术] by (71.8m points)

node.js - Verify and select the right object in an array thanks to a find method which will match with a param json

I need some help,

I've got a json with some parameters inside of it, actually 2 but one day we may add some more in it.

I want to find between some object in an array the right one thanks to all parameters in the json

Am i using the right method ?

to be clearer, i want the param.t to match with the element.t, and the param.tid to match with the element.tid and if moving forward one more parameter cd1 is added to the JSON, this param.cd1 will match with element.cd1

thanks for the time !

const array1 = [{"t":"pageview","de":"UTF-8","tid":"UA-xxxxxxxxxx-17","cd1":"Without cookie"},{"t":"timing","de":"UTF-8","tid":"UA-xxxxxxxx-1","cd1":"France"}];
const param = { t: 'pageview', tid: 'UA-xxxxxxxxxx-17' }

for (let [key, value] of Object.entries(param)) {
  console.log(`${key}: ${value}`);
}
const obj = array1.find(element => element.t == param.t); 
question from:https://stackoverflow.com/questions/65844301/verify-and-select-the-right-object-in-an-array-thanks-to-a-find-method-which-wil

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If I am following correctly, you want to compare an array of objects to an object and based on some keys in 'param' object you want to filter out your array1.

const array2 = [{"t":"pageview","de":"UTF-8","tid":"UA-xxxxxxxxxx-17","cd1":"Without cookie"},{"t":"timing","de":"UTF-8","tid":"UA-xxxxxxxx-1","cd1":"France"}];
const param1 = { t: 'pageview', tid: 'UA-xxxxxxxxxx-17' }

const test = array2.find(checkExist);

const checkExist = el => {
return el.t == param1.t && el.tid == param1.tid; // here you can add your keys in future
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...