gainsky
gainsky

Reputation: 175

How to return json object by variable?

I want to return from JSON object "mail" for "name" which will be definie by variable C.

var c = "product3"

var text = '{"products":[' +
'{"name":"product1","mail":"[email protected]" },' +
'{"name":"product2","mail":"[email protected]" },' +
'{"name":"product3","mail":"[email protected]" }]}';

In this case i want to return product3 [email protected]

Upvotes: 1

Views: 2157

Answers (5)

Debabrata Mohanta
Debabrata Mohanta

Reputation: 645

Using ES2015

let productsArr = JSON.parse(text).products;
let result=productsArr.find(product=>product.name===c);
console.log(result.mail);// output [email protected]

Upvotes: 1

kweku360
kweku360

Reputation: 1075

first change var text to

var text = {"products": [
{"name":"product1","mail":"[email protected]" },
{"name":"product2","mail":"[email protected]" },
{"name":"product3","mail":"[email protected]" }
]};
then you can access the values as follows

var c = text.products[2].name  //returns product3 
var email = text.products[2].mail  //returns [email protected]

Hope this helps.

Upvotes: 0

guradio
guradio

Reputation: 15555

var text = '{"products":[' +
  '{"name":"product1","mail":"[email protected]" },' +
  '{"name":"product2","mail":"[email protected]" },' +
  '{"name":"product3","mail":"[email protected]" }]}';

var data = JSON.parse(text);
var data1 = data.products;
console.log(data1[2].name)//get 3rd
console.log(data1[2].mail)//get 3rd
for (var i = 0; i < data1.length; i++) {
  console.log(data1[i].name)//iterate here
  console.log(data1[i].mail)//iterate here
}

Do it like this

Upvotes: 0

Joey Ciechanowicz
Joey Ciechanowicz

Reputation: 3663

You can use Array.prototype.filter to return only values of your array which have a name === "product3".

var obj = JSON.parse(text);
var c = "product3";

var requiredProduct = obj.products.filter(function(x) { 
  return x.name === c;
});

Upvotes: 0

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

You can do it with ES6's find easily,

var textObj = JSON.parse(text)
var mail = textObj.products.find(itm => itm.name == c).mail
console.log(mail); // "[email protected]"

DEMO

Upvotes: 0

Related Questions