How to get only one value in Javascript array of objects using for of and for in statements?

Viewed 1602

Here is my array of objects, where I want to get specific value.

  { customerName: "Jay", Purchased: "phone", Price: "€200" },
  { customerName: "Leo", Purchased: "car", Price: "€2000" },
  { customerName: "Luk", Purchased: "Xbox", Price: "€400" },
];

in this function I get all values together. But I want specific value in order to show smth like this in console using for of and for in statements. "Dear Jay thank you for purchase of a phone for the price of €200 "

function getValue(){
 for(let key of customerData){
for(let value in key){
  console.log(key[value]) //I get all values 
  //console.log(value)  // I get all keys
}
 }
}

getValue();```
4 Answers

You don't need multiple for loop for this. You can do this using one forEach() loop and template literal like:

var customerData = [{ customerName: "Jay", Purchased: "phone", Price: "€200" },
  { customerName: "Leo", Purchased: "car", Price: "€2000" },
  { customerName: "Luk", Purchased: "Xbox", Price: "€400" },
];

function getValue() {
  customerData.forEach(x => {
    console.log(`Dear ${x.customerName} thank you for purchase of a ${x.Purchased} for the price of ${x.Price}`)
  })
}

getValue();

var customerData = [{ customerName: "Jay", Purchased: "phone", Price: "€200" },
  { customerName: "Leo", Purchased: "car", Price: "€2000" },
  { customerName: "Luk", Purchased: "Xbox", Price: "€400" },
]
    function getValue(){
         for(let key of customerData){
        for(let value in key){
          console.log(key[value]) //I get all values 
          break;
        //It Work
        }
         }
        }
    
        getValue();

By passing the object position in the array as a parameter for the function you can get the single object keys

function getValue(data){
    for(let key of Object.values(data)){
        console.log(key)
    }
}

getValue(a[1]);

// Output Leo car €2000

You need to pass the name of the customer you're looking for and the data you want about them. Then you can use Array.filter() and Array.map()

Then you can put the functions into a template literal to get your result.

let customerData=[{customerName:"Jay",Purchased:"phone",Price:"€200"},{customerName:"Leo",Purchased:"car",Price:"€2000"},{customerName:"Luk",Purchased:"Xbox",Price:"€400"}]

function getValue(name, otherKey) {
  return customerData.filter(obj => obj.customerName === name).map(obj => obj[otherKey])[0]
}

console.log(getValue("Jay", "Purchased"))
console.log(getValue("Luk", "Price"))


let str = `Dear Jay thank you for purchase of a ${getValue("Jay", "Purchased")} for the price of ${getValue("Jay", "Price")}`

console.log(str)

Related