1

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]

2
  • what have you already tried? where is your code? Commented Apr 12, 2016 at 9:59
  • 2
    why do you use a string and not an object literal? Commented Apr 12, 2016 at 9:59

5 Answers 5

1

Using ES2015

let productsArr = JSON.parse(text).products;
let result=productsArr.find(product=>product.name===c);
console.log(result.mail);// output [email protected]
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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;
});

Comments

0

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

Comments

0

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.