简体   繁体   中英

matching an object with its corresponding value in an array

Here is the problem...

Create a function called keyAccessor. keyAccessor should take in two parameters: an array of people, and an object. Each person's name is also a property on an object. keyAccessor should loop through the array of names, and access corresponding values for each name in the object, pushing the values into an empty array. keyAccessor should return the new array.

Example set of names that could be passed in

var names = ["Dan", "Todd", "Andrew", "Doug"]

Example object that could be passed in

var people = {
  Dan: { city: "Las Vegas", age: 24 },
  Todd: { city: "France", age: 28 },
  Andrew: { city: "Portland", age: 12 },
  Doug: { city: "New New York", age: 56 },
}

Example new array that would be returned

var sampleOutput = [
  { city: "Las Vegas", age: 24 },
  { city: "France", age: 28 },
  { city: "Portland", age: 12 },
  { city: "New New York", age: 56 }
]

This is how far I have got.

 function keyAccessor(arr, obj){ var newArr = [] console.log(obj) console.log(arr) for(let i=0;i<arr.length;i++){ if(arr[i]=obj.name){ return newArr.push(obj) } } return newArr }

Since this question is really simple, you probably don't need a standalone function.
Using map should be enough.

 const names = ["Todd", "Dan", "Andrew", "Doug"]; const people = { Dan: { city: "Las Vegas", age: 24 }, Todd: { city: "France", age: 28 }, Andrew: { city: "Portland", age: 12 }, Doug: { city: "New New York", age: 56 }, }; function keyAccessor(names, people) { return names.map(name => people[name]); } console.log(keyAccessor(names, people));

The code above equivalents to:

 let result = []; for(let index in names) { // in this case, index will be 1, 2, 3, 4 let name = names[index]; result.push(people[name]); }

names.map(name => people[name]); is shorthand for names.map(name => { return (people[name]); });
Since the name is the key for people object, people.Dan and people['Dan'] will return same 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