简体   繁体   中英

How can I create a new array by iterating an existing array over a json config 'key'?

I have an array of numbers in a string in an array named data and cannot figure out how to use the data to iterate over my JSON named key .

I've attempted some variations of a for loop, but am not able to:

  1. Strip out the desired data, it shows up errors for numbers
  2. I haven't been able to design a loop which iterates over the array values, just 1 to 5. The array changes so it could be ["5", "2", "3"]

Is anyone able to please help? Many thanks.

   var key = {
    "1" : "ID 1: Steve",
    "2" : "ID 2: Bob",
    "3" : "ID 3: Paul",
    "4" : "ID 4: Spencer",
    "5" : "ID 5: Jimmy"}; 

   data = ["1", "3", "5"]

desired output: ["ID 1: Steve", "ID 3: Paul", "ID 5: Jimmy"]

Just iterate over the data array and get all the values from the object key as an array, here is an example

 var key = { "1": "ID 1: Steve", "2": "ID 2: Bob", "3": "ID 3: Paul", "4": "ID 4: Spencer", "5": "ID 5: Jimmy" }; var data = ["1", "3", "5"]; var newArr = data.map(n => key[n]); console.log(newArr);

Another solution using: for...in to iterate on properties of key . Then if that property exists via Array.includes in data add it to result

 let key = { "1": "ID 1: Steve", "2": "ID 2: Bob", "3": "ID 3: Paul", "4": "ID 4: Spencer", "5": "ID 5: Jimmy" }; let data = ["1", "3", "5"]; let result = []; for (const k in key) { if (data.includes(k)) { result.push(key[k]); } } console.log("result::", result);

A better approach based on comments: Iterate on data for...of and pick value from key object

 let key = { "1": "ID 1: Steve", "2": "ID 2: Bob", "3": "ID 3: Paul", "4": "ID 4: Spencer", "5": "ID 5: Jimmy" }; let data = ["1", "3", "5"]; let result = []; for (const d of data) { result.push(key[d]); } console.log("result::", result);

You could use a reduce to achieve this:

 const key = { "1": "ID 1: Steve", "2": "ID 2: Bob", "3": "ID 3: Paul", "4": "ID 4: Spencer", "5": "ID 5: Jimmy"}; const data = ["1", "3", "5"]; const result = data.reduce((accum, i) => { accum.push(key[i]); return accum; }, []); console.log(result);

 var key = { "1": "ID 1: Steve", "2": "ID 2: Bob", "3": "ID 3: Paul", "4": "ID 4: Spencer", "5": "ID 5: Jimmy"}; // const desired = ["ID 1: Steve", "ID 3: Paul", "ID 5: Jimmy"] const data = ["1", "3", "5"] const result = [] const values = Object.values(key) //console.log(values); data.forEach(item => { values.forEach(val => { if (val.includes('ID ' + item + ':')) { result.push(val) } }) }) console.log(result);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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