How convert javascript _proto_ object to json - javascript

How can we convert javascript __proto__ object to a json string output
this.products.forEach(function(element, index) {
productsInfo.push(productsFormItems[index].myFunction());
});
console.log(JSON.stringify(productsInfo));
myFunction() {
let result = Object.create({
ProductName: { value: this.formData.ProductName },
Address: { value: this.formData.Address }
});
return result;
}
See the sample example below:
Required json format:
"productInfo":[
{
"ProductName":"Testdata"
"Address":"TestValue"
}
]
[
{
"ProductName":"Testdata"
"Address":"TestValue"
}
]

Related

Filter an array of object based on key name of the object

I have an array of objects that looks like this:
var data = [
{
abc: { name:"abc" }
},
{
new_abc: {name:"hello" }
},
{
def: { name:"def" }
},
{
ghi: { name:"ghi" }
},
{
new_ghi: { name:"world" }
},
{
new_jkl: { name:"javascript" }
},
{
lmn: { name:"lmn" }
},
];
I want only the objects that have a key whose name starts with "new". In the above array, I have 3 such objects.
I want the output to be this:
[
{
new_abc:{name:"hello"}
},
{
new_ghi:{name:"world"}
},
{
new_jkl:{name:"javascript"}
},
]
You can do the following,
var data = [
{
abc:{name:"abc"}
},
{
new_abc:{name:"hello"}
},
{
def:{name:"def"}
},
{
ghi:{name:"ghi"}
},
{
new_ghi:{name:"world"}
},
{
new_jkl:{name:"javascript"}
},
{
lmn:{name:"lmn"}
}
]
res = data.filter(item => Object.keys(item).some(key => key.indexOf('new') === 0));
console.log(res);
I want only the objects that have a key whose name starts with "new"
You can use Array#filter combined with String.prototype.startsWith() like this way.
const data = [{abc:{name:"abc"}},{new_abc:{name:"hello"}},{def:{name:"def"}},{ghi:{name:"ghi"}},{new_ghi:{name:"world"}},{new_jkl:{name:"javascript"}},{lmn:{name:"lmn"}}];
console.log(data.filter(item => Object.keys(item)[0].startsWith('new')));
The startsWith() method determines whether a string begins with the
characters of a specified string, returning true or false as
appropriate.

How to create interface adapter in typescript?

I want to replace client json into my json
client JSON
interface Cols {
displayName: string;
}
{
cols:[
{
displayName: 'abc';
}
]
}
my JSON
interface Cols {
label: string;
}
{
cols:[
{
label:'z';
}
]
}
I want to replace z into abc
to replace your value directly,
const a = {
cols:[
{
label:'z'
}
]
}
a.cols[0].label = 'abc'
from client json you wanted to replace with ypu can use:
const a = {
cols:[
{
label:'z'
}
]
}
//clients json
const b = {
cols:[
{
displayName: 'def'
}
]
}
//for static array
a.cols[0].label = b.cols[0].displayName
for more than 1 item in array, you need to put it in a loop or map

javascript filter by object key and return value of nested object key

I want to return the value of a key for one of the elements inside the object using a condition:
const raw = {
item1: { name: 'sdfd1', otherStuff: { book:'sdfd11' } },
item2: { name: 'sdfd2', otherStuff: { book:'sdfd22' } },
item3: { name: 'sdfd3', otherStuff: { book:'sdfd33' } }
};
var anotherOne = {
country1 : { city: 'one', item: 'item3'},
country2 : { city: 'two', item: 'item4'}
}
var searchTerm = anotherOne.country1.item; // item3
var secondTerm = someUser.otherInfo // 'otherStuff'
var result = Object.keys(raw)
.filter(key => {
if (key === searchTerm){
return raw[searchTerm][secondTerm].book
}})
console.log('result:' result); // sdfd33
Basically, i want to look for the searchTerm in the keys of the object raw, and return the value for the book key. In this example, it should return sdfd33.
My attempt is returning nothing.
updated:
updated the question.
Use square bracket [] while accessing a object key through a variable.
Hopefully the filter & Object.keys will not be required in this case
const raw = {
item1: {
name: 'sdfd1',
book: 'sdfd11'
},
item2: {
name: 'sdfd2',
book: 'sdfd22'
},
item3: {
name: 'sdfd3',
book: 'sdfd33'
}
};
var searchTerm = 'item3';
//using square bracket when acceing key using variable
var result = raw[searchTerm].book
console.log(result);
You can simply return the value like :
var result = raw.item3.book;
console.log(result);
result should be sdfd33

how do i print values in nested json array using node.js?

i have this json array.
[ { '0': { msg: 'helloworld1' } }, { '0': { msg: 'helloworld2' } } ]
and here I'm trying to console log the value of every msg by doing this.
jsonArray.forEach(function(element) {
console.log(element);
console.log(element['0']);
});
output
{ '0': { msg: 'helloworld1' } }
{ '0': { msg: 'helloworld2' } }
undefined
undefined
the question is, how do i print out the values of msg keys and why is it returning undefined?
Try to parse the data again as following:
var jsonArray = [ { '0': { msg: 'helloworld1' } }, { '0': { msg: 'helloworld2' } } ]
jsonArray = JSON.parse(JSON.stringify(jsonArray));
jsonArray.forEach(function(element) {
console.log(element['0'].msg);
});
This JSON.stringify should convert the data to string then JSON.parse will convert it to JS Object.
You can use lodash for this.
var array = [ { '0': { msg: 'helloworld1' } }, { '0': { msg: 'helloworld2' } } ];
_.mapValues(array, function(array2) {
_.mapValues(array2, function(array3){
console.log(array3.msg)})
})
This will return the value in 'msg' keys. Here is the lodash documentation. loadh-map
You have no problem at all, apparently.
Check out: https://repl.it/Gh3i/0
If you click 'run' you get
helloworld1
helloworld2
The same applies if you use integers:
var jsonArray = [ { '0': { msg: 'helloworld1' } }, { '0': { msg: 'helloworld2' } } ];
jsonArray.forEach(function(element) {
console.log(element[0].msg);
});
Please find the updated code attached below
var jsonArray=[{"0":{"msg":"helloworld1"}},{"0":{"msg":"helloworld2"}}];
jsonArray.forEach(function(element) {
console.log(element[0].msg);
});

read json values from ajax success?

I am getting JSON data like below example. Now I want get each value in separate variables like
var reviewDate ='2015-06-01T05:00:00Z'
var developers ='Ankur Shah,Srikanth Vadlakonda,Tony Liu, Qiuming Jie
var reviewers = 'mike,john'
var title='Test project'
var call =$.ajax({
url:url,
type:"GET",
dataType:"json",
headers:{
Accept:"application/json;odata=verbose"
}
});
call.done(function(data,textStatus,jqXHR){
alert("Success!! "+ jqXHR.responseText);
});
call.fail(function(jqXHR,textStatus,errorThrown){
alert("Error retriving Tasks!! "+ jqXHR.responseText);
});
I am getting results in call.done in . How to set those values?
You could do something along these lines:
http://jsfiddle.net/e0mfc1rd/2/
Javascript:
var data = {
results: {
Date_x0020_of_x0020_Review: '2015-06-01T05:00:00Z',
Name_x0020_of_x0020_Developers: {
results: [
{
__metadata: {},
Title: 'Ankur Shah'
},
{
__metadata: {},
Title: 'Tony Liu'
},
{
__metadata: {},
Title: 'Qiuming Jie'
}
]
},
Name_x0020_of_x0020_Reviewers: {
results: [
{
__metadata: {},
Title: 'Mike'
},
{
__metadata: {},
Title: 'John'
}
]
}
}
}
// map the key names.
// you could do something more clever here, like just extracting
// the segment after the last underscore using substring or a regex,
// but for this example we'll do a simple map.
var names = {
'Name_x0020_of_x0020_Reviewers': 'reviewers',
'Name_x0020_of_x0020_Developers': 'developers'
}
// a variable to hold the result.
var processed = {};
// iterate over each key in data.results
// (e.g. 'Name_x0020_of_x0020_Developers', 'Name_x0020_of_x0020_Reviewers', etc.)
Object.keys(data.results).forEach(function(k) {
// if the object indexed at that key has a 'results' property that is an array...
if (Array.isArray((data.results[k] || {}).results)) {
// pluck the Title attribute from each of those entries into a new array.
var values = data.results[k].results;
var titles = values.map(function(v) {
return v.Title;
});
// translate keys like 'Name_x0020_of_x0020_Reviewers'
// into something more palatable
var key = names[k] || k;
// join the titles into a string, separated by a comma
processed[key] = titles.join(',');
}
else if (k.indexOf('Date') === 0) { // key starts with 'Date'
processed[k] = new Date(data.results[k]);
}
});
After which the variable 'processed' would contain:
{
"Date_x0020_of_x0020_Review": "2015-06-01T05:00:00.000Z",
"developers": "Ankur Shah,Tony Liu,Qiuming Jie",
"reviewers": "Mike,John"
}
You could also use UnderscoreJS to get your data from your JSON.
You need to chain some pluck calls and you should get to your data.
Please find the demo below and here at jsFiddle.
To get the parsed object into your comma separated format just use for example: var developers = parsed.developers.join(',');
var resultJSON = {
d: {
__metadata: {},
"Name_x0020_of_x0020_Developers": {
"results": [{
"Title": "Ankur Shah"
}, {
"Title": "Srikanth"
}, {
"Title": "Tony Liu"
}]
},
"Name_x0020_of_x0020_Reviewers": {
"results": [{
"Title": "Name1"
}, {
"Title": "Name2"
}, {
"Title": "Name3"
}]
}
}
};
//console.log(resultJSON);
var names = {
developers: 'Name_x0020_of_x0020_Developers',
reviewers: 'Name_x0020_of_x0020_Reviewers'
};
var parsed = {};
_.each(names, function (name, key) {
parsed[key] = _.chain(resultJSON) // key is developers, reviewers
.pluck(name) // is the name in the JSON e.g. Name_..._Developers
.pluck('results')
.tap(function (data) { // tap is optional and can be removed
console.log('before flatten', data); // it shows the nesting [[]]
})
.flatten(true) // used to remove outer array
.tap(function (data) {
// we now have the result. Next, get the title
console.log('before getting the Title', data);
})
.pluck('Title')
.value();
});
console.log(parsed);
document.getElementById('output').innerHTML = JSON.stringify(parsed, null, 2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<pre id="output"></pre>

Categories

Resources