How to retrive property values from array of objects in javascript - javascript

[{
"circlemarker": [{
"type": "circle_marker"
}, {
"latlong": "abc"
}]
}, {
"connector_marker": [{
"type": "icon_marker"
}, {
"latlong": "pqr"
}]
}, {
"icon_marker": [{
"type": "connector_marker"
}, {
"latlong": "xyz"
}]
}]
I want to access latlong values of each marker. So how can I have access to each property in this structure.

You can get latlong data:
for (var a = 0; a < obj.length; a++) {
var key = Object.keys(obj[a])[0];
var latlong = obj[a][key][1];
console.log(latlong));
}
But i think that data have not correct structure, this is better solution:
var markers = [{
"name": "circlemarker",
"type": "circle_marker"
"latlong": "abc"
}, {
"name": "connector_marker",
"type": "icon_marker",
"latlong": "pqr"
}, {
"name": "icon_marker",
"type": "connector_marker",
"latlong": "xyz"
}];

I think this should work for you:-
var makers = [{"circlemarker":[{"type":"circle_marker"},{"latlong":"abc"}]},{"connector_marker":[{"type":"icon_marker"},{"latlong":"pqr"}]},{"icon_marker":[{"type":"connector_marker"},{"latlong":"xyz"}]}];
makers.forEach(function(maker){
var makerName = Object.keys(maker)[0];
console.log(maker[makerName][1]["latlong"]);
});

so for each object in the array, you want to pluck the latlong from the first key which also references another array of objects. Man I would fix this data structure but if you can't control it, you can do this:
#!/usr/bin/env node
var data = [{
"circlemarker": [{
"type": "circle_marker"
}, {
"latlong": "abc"
}]
}, {
"connector_marker": [{
"type": "icon_marker"
}, {
"latlong": "pqr"
}]
}, {
"icon_marker": [{
"type": "connector_marker"
}, {
"latlong": "xyz"
}]
}];
var _ = require('lodash')
, coords = [];
_.each(data, function(item){
//console.log(item);
var key = _(Object.keys(item)).first()
, first = item[key]
, latLong = _.pluck(first, 'latlong')[1];
if ( latLong ) {
coords.push(latLong);
}
});
console.log(coords);
Produces the following output:
[ 'abc', 'pqr', 'xyz' ]

Related

Create JSON dynamically with dynamic keys and values in Express Js

I am fetching API into my Express server which has several JSON key value pairs in one array.
For Example:
[{
"quality": "best",
"url": "https://someurlhere.example/?someparameters"
},
{
"quality": "medium",
"url": "https://someurlhere1.example/?someparameters"
}]
And I want to create an array of JSON of that received data in this Format:
[{
"best": "https://someurlhere.example/?someparameters"
},
{
"medium": "https://someurlhere1.example/?someparameters"
}]
I have tried doing this by using for loop
for(let i=0; i < formats.length; i++){
arr.push({
`${formats[i].quality}` : `${formats[i].url}`
})
}
But it didn't work for me.
Please help me in achieving this.
Thanks in Advance :)
You could use the map function and create a new object from it.
For example:
let prevArr = [{
"quality": "best",
"url": "https://someurlhere.example/?someparameters"
}, {
"quality": "medium",
"url": "https://someurlhere1.example/?someparameters"
}]; // Replace with your array
let newArr = [];
let obj = {};
prevArr.map(function(x) {
obj = {};
obj[x["quality"]] = x.url;
newArr.push(obj);
});
const input = [{
"quality": "best",
"url": "https://someurlhere.example/?someparameters"
}, {
"quality": "medium",
"url": "https://someurlhere1.example/?someparameters"
}];
const result = input.map((v, i) => {
return {
[v["quality"]]: v["url"]
}
});
console.log(result)

Extract only key names from JSON in array format using nodejs

How to get JSON data key names in a array format using nodejs?
I've tried the following but it returns object. But I want an array so I can store it in a varaible.
const jsondata = [{ "name": "StorageType", "value": "AllStorageTypes" }, { "name": "BucketName", "value": "testing" }]
Object.keys(jsondata).forEach(function(key) {
var value = jsondata[key];
console.log(value)
});
output:
{ name: 'StorageType', value: 'AllStorageTypes' }
{ name: 'BucketName', value: 'testing' }
Expected output:
["StorageType", "BucketName"]
Try this
const jsondata = [{ "name": "StorageType", "value": "AllStorageTypes" }, { "name": "BucketName", "value": "testing" }]
const arrayData = jsondata.map(item => item.name)
console.log(arrayData)
jsondata.map(obj=>obj.name)

How to add new key value pair to an object in an array based on another key-value

I have 2 JSON objects:
obj1 = [{
"screenCode": "usr_ooo_master",
"screenName": "Out Of Office Master"
}, {
"screenCode": "usr_user_master",
"screenName": "User Master"
}]
obj2 = [{
"id": "10a310a8-6f01-4082-af86-bb73019cff8d",
"cascadeImpact": {
"screenCode": "usr_user_master",
"impactedModuleCode": "borrower2"
},
"screenImpactedCode": "bor_address1"
}, {
"id": "308c8058-5e98-4b99-a1c6-82e9e5c93787",
"cascadeImpact": {
"screenCode": "usr_ooo_master",
"impactedModuleCode": "borrower2"
},
"screenImpactedCode": "bor_address2"
}]
I want to add a new key-value pair to obj2 depending on the "screenCode". So eg. I want to add "screenName": "User Master" to obj2 first element. How do I do that.
You could move the corresponding key/values pairs to a Map and update the object with the result of the map.
var array1 = [{ screenCode: "usr_ooo_master", screenName: "Out Of Office Master" }, { screenCode: "usr_user_master", screenName: "User Master" }],
array2 = [{ id: "10a310a8-6f01-4082-af86-bb73019cff8d", cascadeImpact: { screenCode: "usr_user_master", impactedModuleCode: "borrower2" }, screenImpactedCode: "bor_address1" }, { id: "308c8058-5e98-4b99-a1c6-82e9e5c93787", cascadeImpact: { screenCode: "usr_ooo_master", impactedModuleCode: "borrower2" }, screenImpactedCode: "bor_address2" }],
map = new Map(array1.map(({ screenCode, screenName }) => [screenCode, screenName]));
array2.forEach(({ cascadeImpact }) =>
cascadeImpact.screenName = map.get(cascadeImpact.screenCode));
console.log(array2);
.as-console-wrapper { max-height: 100% !important; top: 0; }
obj2['screenName'] = 'User Master'
The only thing I a little but doubt is within obj2 you have single-element array. If the above won't work, you can always iterate on obj2 like (JQuery version):
$.each(obj2, function(index, element) {
element['screenName'] = 'User Master';
}
Having in mind you olny have 1 element in the array - it will iterate only once (but the resource hunger will be larger than if you just do the assignment like in the first code)
if u want to add key to specific item just use key of that item: obj2[0]['screenName'] = "test" otherwise there is loop down below:
obj2 = [{
"id": "10a310a8-6f01-4082-af86-bb73019cff8d",
"cascadeImpact": {
"screenCode": "usr_user_master",
"impactedModuleCode": "borrower2"
},
"screenImpactedCode": "bor_address1"
}, {
"id": "308c8058-5e98-4b99-a1c6-82e9e5c93787",
"cascadeImpact": {
"screenCode": "usr_ooo_master",
"impactedModuleCode": "borrower2"
},
"screenImpactedCode": "bor_address2"
}]
for(var i=0;i < obj2.length; i++){
obj2[i]['screenName'] = 'Master-' + (i+1);
obj2[i]['screenCode'] = 'Code-' + (i+1);
}
console.log(obj2)

How to convert Json into associative array or key value array

I have following Json which i need to insert into a table.
I want to convert each student detail into a row.
Because if i loop through the rows as per the existing structure i am reading one column as a row.
var json {
"Students":[
{
"name":{
"value":"Allan"
},
"number":{
"value":"123"
}
},
{
"name":{
"value":"Frank"
},
"number":{
"value":"456"
}
}
]
}
Ideally i want to the above as
{ "name": "Allan", "number": 123};
{ "name": "Frank", "number": 456};
I am looping through the Json as below
var objectKeys = Object.keys(json);
for (var key in objectKeys)
{
var student = json.Students;
for (var i = 0; i < student .length; i++) {
for (var column in json.Students[i]) {
window.print(column);
window.print(json.Students[i][column].value);
}
}
}
NOTE: No JQuery, want to achieve the above through normal Javascript.
If you want to transform the data, you can use Array.map
var json = {"Students":[{"name":{"value":"Allan"},"number":{"value":"123"}},{"name":{"value":"Frank"},"number":{"value":"456"}}]};
let result = json.Students.map(o => ({
name: o.name.value,
number: o.number.value
}));
console.log(result);
If you want to access the data, you can use Array.forEach
var json = {"Students":[{"name":{"value":"Allan"},"number":{"value":"123"}},{"name":{"value":"Frank"},"number":{"value":"456"}}]};
json.Students.forEach(o => console.log({name: o.name.value, number: o.number.value}));
var json = {
"Students":[
{
"name":{
"value":"Allan"
},
"number":{
"value":"123"
}
},
{
"name":{
"value":"Frank"
},
"number":{
"value":"456"
}
}
]
}
var studentData = JSON.stringify(json.Students);
var convertedData = JSON.parse(studentData.replace(/\{\"value\"\:/g,"").replace(/\}\,\"number/g,',"number').replace(/\"\}\}/g,'"}'));
Try this :)
No map or reduce. Just classic Javascript.
var json = {
"Students": [{
"name": {
"value": "Allan"
},
"number": {
"value": "123"
}
},
{
"name": {
"value": "Frank"
},
"number": {
"value": "456"
}
}
]
};
for (var student of json["Students"]) {
console.log(student); //your logic goes here.
}

Push object keys and its values to array

I have an object like this:
{
"id": 23,
"name": "Jacob",
"link": {
"rel": "self",
"link": "www.abc.com"
},
"company":{
"data":{
"id": 1,
"ref": 324
}
}
I want to store each key with its value to an array in javascript or typescript like this
[["id":23], ["name":"Jacob"], ["link":{......, ......}]] and so on
I am doing this so that I can append an ID for each.
My best guess I would loop through the array and append an ID/a flag for each element, which I don't know how to do as well.... how to address this issue ? thanks
var arr = [];
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
var innerObj = {};
innerObj[prop] = obj[prop];
arr.push(innerObj)
}
}
console.log(arr);
here is demo https://plnkr.co/edit/9PxisCVrhxlurHJYyeIB?p=preview
p.forEach( function (country) {
country.forEach( function (entry) {
entry.push( {"value" : 'Greece', "synonyms" : 'GR'});
});
});
you can try to use experimental Object.entries:
let obj = {
"id": 23,
"name": "Jacob",
"link": {
"rel": "self",
"link": "www.abc.com"
},
"company":{
"data":{
"id": 1,
"ref": 324
}
}};
console.log(Object.entries(obj).map(item => ({[item[0]]:item[1]})));
for unsupported browsers you can use polyfill: https://github.com/es-shims/Object.entries
You could use an iterative/recursive approach with the object and their nested parts. It works for any depths.
function getKeyValue(object) {
return Object.keys(object).reduce(function (result, key) {
return result.concat(
object[key] && typeof object[key] === 'object' ?
getKeyValue(object[key]) :
[[key, object[key]]]
);
}, []);
}
var data = { id: 23, name: "Jacob", link: { rel: "self", link: "www.abc.com" }, company: { data: { id: 1, ref: 324 } } };
console.log(getKeyValue(data));
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can use the Object.keys method to get an array of the keys, then use the Array#map method to return a new array containing individual objects for each property.
This ES6 one-liner should do it:
const splitObject = o => Object.keys(o).map(e => ({ [e]: o[e] }));
Or in ES5:
function splitObject(o) {
return Object.keys(o).map(function(e) {
return Object.defineProperty({}, e, {
value: o[e],
enumerable: true
});
});
}
var res = [];
_.transform( {
"id": 23,
"name": "Jacob",
"link": {
"rel": "self",
"link": "www.abc.com"
},
"company": {
"data": {
"id": 1,
"ref": 324
}
}
}, function(result, value, key) {
res.push(key +':'+value);
}, {});
You can use underscore
Supported in all major browser, including IE11
Object.entries() gives you exactly this.
const obj = {
id: 23,
name: 'Jacob',
link: {
rel: 'self',
link: 'www.abc.com'
},
company: {
data: {
id: 1,
ref: 324
}
}
};
Object.entries(obj);
// output:
[
[
"id",
23
],
[
"name",
"Jacob"
],
[
"link",
{
"rel": "self",
"link": "www.abc.com"
}
],
[
"company",
{
"data": {
"id": 1,
"ref": 324
}
}
]
]
var obj=[{"Name":ABC,"Count":123},{"Name":XYZ,"Count":456}];
var arr = [];
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
var innerObj = {};
innerObj[0] = obj[prop];
arr.push(innerObj[0]);
}
}
/* Here above exmple innerobj index set to 0 then we will get same data into arr if u not menstion then arr will conatins arr[0] our result.
then we need to call first record obj arr[0][0] like this*/
const foo = { "bar": "foobar", "foo": "foobar" }
Object.entries(foo)
should result in:
[["bar", "foobar"], ["foo", "foobar"]]
maybe there's a function to pass to convert all commas to colons
Here's the documentation
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries

Categories