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]

asked Apr 12, 2016 at 9:57
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]
answered Apr 13, 2016 at 7:19
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

answered Apr 12, 2016 at 10:00

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;
});
answered Apr 12, 2016 at 10:00

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

answered Apr 12, 2016 at 10:08

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.

answered Apr 12, 2016 at 10:12

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.