I would like to transform the below JSon. The input JSon array can be of any size. I know its a basic question but I can't find the duplicate.
var input = [{
"value": 1
}, {
"value": 2
}]
var output = [{
"key": {
"value": 1
}
}, {
"key": {
"value": 2
}
}]
Appreciate all the help.
Create a new array and use Array#forEach to push an object with key = key and a currently iterated object from input as the value.
var input = [{value:1},{value:2}],
result = [];
input.forEach(v => result.push({ 'key': v }));
console.log(result);
Try using this, this should solve your problem
output = input.map(value => ({ "key": value }) );
console.log(output);
I used ES6 for simplicity, but this does exactly the same.
I think this will be the most oldschool and hands-on way of doing this.
var input = [{
"value": 1
}, {
"value": 2
}],
output = [],
newItem,
i = 0, ii = input.length;
for(i; i<ii; i++){
newItem = {};
newItem.key = {"value":input[i].value};
output.push(newItem);
}
console.log(output)
Related
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)
I need to check if the duplicate key value present inside the json array using Angular.js. I am explaining my code below.
var result=[{
"email":'a#gmail.com',
"title":'hello',
"start":'yes'
},{
"email":'a#gmail.com',
"title":'hello',
"start":'yes'
},{
"email":'b#gmail.com',
"title":'ggggg',
"start":'No'
},{
"email":'g#gmail.com',
"title":'hel',
"start":'No'
},{
"email":'b#gmail.com',
"title":'ggggg',
"start":'No'
}];
if (result.length > 0) {
angular.forEach(result,function(obj2){
var data={'title':obj2.mname,'start':obj2.date};
evtArr.push(data);
})
}
Here my requirement is before pushing the data into evtArr it will check the duplicate value using the key- email if one set of value belongs to one email (i.e-a#gmail.com) is already pushed into evtArr then other will remove.
You can use array#reduce and create an object using email as key and object as value. Take out all the values from the object using Object.values().
var result=[{ "email":'a#gmail.com', "title":'hello', "start":'yes' },{ "email":'a#gmail.com', "title":'hello', "start":'yes' },{ "email":'b#gmail.com', "title":'ggggg', "start":'No' },{ "email":'g#gmail.com', "title":'hel', "start":'No' },{ "email":'b#gmail.com',"title":'ggggg', "start":'No' }],
output = Object.values(result.reduce((r,o) => {
r[o.email] = Object.assign({},o);
return r;
},{}));
console.log(output);
Here below is a simple and easy to understand solution for you.
First, push only the results into resultFinal array if the result with same email is not already pushed into that array.
let resultFinal = [];
result.forEach((resI) => {
if (resultFinal.findIndex(resF => resF.email === resI.email) === -1) {
resultFinal.push(result);
}
});
After you have your resultFinal array, run a map and return objects comprising only of title and start for each of the elements.
resultFinal = resultFinal.map((resF) => {
return {title: resultf.title, start: resultf.start};
});
Hope this helps you.
Try this Code.understand easily
var result = [{
"email": 'a#gmail.com',
"title": 'hello',
"start": 'yes'
}, {
"email": 'a#gmail.com',
"title": 'hello',
"start": 'yes'
}, {
"email": 'b#gmail.com',
"title": 'ggggg',
"start": 'No'
}, {
"email": 'g#gmail.com',
"title": 'hel',
"start": 'No'
}, {
"email": 'b#gmail.com',
"title": 'ggggg',
"start": 'No'
}];
if (result.length > 0) {
var ArrayPush = [];
for (i = 0; i < result.length; i++) {
var obj = {}
obj.email = result[i].email;
obj.title = result[i].title;
obj.start = result[i].start;
var Getdistinctdate=ArrayPush.filter(function(element){
return element.email==result[i].email;
});
if(Getdistinctdate.length==0){
ArrayPush.push(obj);
}
}
}
This question already has answers here:
Convert array of object to object with keys
(2 answers)
Closed 6 years ago.
One of the possible outputs for my service is as follows.
[{
"key": 1,
"val": 0
}, {
"key": 2,
"val": 0
}]
Is there a function that can convert this to an object like the one below?
{
"1":0,
"2":0
}
My purpose is to be able to read the object values as a map, such as o["1"], i.e.: if (o["1"] == 0) {....
You can do this with reduce
var data = [{"key": 1, "val": 0}, {"key": 2, "val": 0}];
var result = data.reduce((obj, e) => {
obj[e.key]= e.val;
return obj;
}, {});
console.log(result)
You could iterate over with Array#forEach and assign the wanted properties with the value.
var array = [{ "key": 1, "val": 0 }, { "key": 2, "val": 0 }],
object = {};
array.forEach(function (a) {
object[a.key] = a.val;
});
document.write('<pre>' + JSON.stringify(object, 0, 4) + '</pre>');
You can do it in javascript with
target = {};
source.forEach(function(e) {
target[e.key] = e.val;
});
I don't think there is one in pure Javascript. Maybe some library like jQuery will have something like that. You can do your own with little code, though. In pure JS:
var o = {};
for (var i = 0; i < json.length; i++) {
o[json[i].key] = json[i].val;
}
I have data that's in this format:
{
"columns": [
{
"values": [
{
"data": [
"Project Name",
"Owner",
"Creation Date",
"Completed Tasks"
]
}
]
}
],
"rows": [
{
"values": [
{
"data": [
"My Project 1",
"Franklin",
"7/1/2015",
"387"
]
}
]
},
{
"values": [
{
"data": [
"My Project 2",
"Beth",
"7/12/2015",
"402"
]
}
]
}
]
}
Is there some super short/easy way I can format it like so:
{
"projects": [
{
"projectName": "My Project 1",
"owner": "Franklin",
"creationDate": "7/1/2015",
"completedTasks": "387"
},
{
"projectName": "My Project 2",
"owner": "Beth",
"creationDate": "7/12/2015",
"completedTasks": "402"
}
]
}
I've already got the column name translation code:
r = s.replace(/\%/g, 'Perc')
.replace(/^[0-9A-Z]/g, function (x) {
return x.toLowerCase();
}).replace(/[\(\)\s]/g, '');
Before I dive into this with a bunch of forEach loops, I was wondering if there was a super quick way to transform this. I'm open to using libraries such as Underscore.
function translate(str) {
return str.replace(/\%/g, 'Perc')
.replace(/^[0-9A-Z]/g, function (x) {
return x.toLowerCase();
})
.replace(/[\(\)\s]/g, '');
}
function newFormat(obj) {
// grab the column names
var colNames = obj.columns[0].values[0].data;
// create a new temporary array
var out = [];
var rows = obj.rows;
// loop over the rows
rows.forEach(function (row) {
var record = row.values[0].data;
// create a new object, loop over the existing array elements
// and add them to the object using the column names as keys
var newRec = {};
for (var i = 0, l = record.length; i < l; i++) {
newRec[translate(colNames[i])] = record[i];
}
// push the new object to the array
out.push(newRec);
});
// return the final object
return { projects: out };
}
DEMO
There is no easy way, and this is really not that complex of an operation, even using for loops. I don't know why you would want to use regex to do this.
I would start with reading out the column values into a numerically indexed array.
So something like:
var sourceData = JSON.parse(yourJSONstring);
var columns = sourceData.columns[0].values[0].data;
Now you have a convenient way to start building your desired object. You can use the columns array created above to provide property key labels in your final object.
var sourceRows = sourceData.rows;
var finalData = {
"projects": []
};
// iterate through rows and write to object
for (i = 0; i < sourceRows.length; i++) {
var sourceRow = sourceRows[i].values.data;
// load data from row in finalData object
for (j = 0; j < sourceRow.length; j++) {
finalData.projects[i][columns[j]] = sourceRow[j];
}
}
That should do the trick for you.
Sorry I'm kind of new to JS; I have an array of object; how can I get the name of the object which has the key "user_key3" and obviously without having a loop and have a condition.
arr = [{
"name": "user1",
"key": "user_key1"
},{
"name": "user3",
"key": "user_key3"
},{
"name": "user2",
"key": "user_key2"
}]
Please let me know if you need more clarification
Thanks
You can do it the functional way, like this
var name;
arr.forEach(function(currentObject) {
if (currentObject.key === "user_key3") {
name = currentObject.name;
}
});
If you want to short-circuit on the first match, you can use Array.prototype.some, like this
var name;
arr.some(function(currentObject) {
if (currentObject.key === "user_key3") {
name = currentObject.name;
return true;
}
return false;
});
The OP had mentioned obviously without having a loop and have a condition. I would do it as below:
arr = [{
"name": "user1",
"key": "user_key1"
},{
"name": "user3",
"key": "user_key3"
},{
"name": "user2",
"key": "user_key2"
}];
var keyValMap = arr.map(function(n) { return n.key } );
var arrIndex = keyValMap.indexOf('user_key3');
alert(arr[arrIndex].name);
Fiddle
You'll have to iterate and check for the key
var user_name;
for (var i=0; i<arr.length; i++) {
if ( arr[i].key === 'user_key3' ) {
user_name = arr[i].name;
break;
}
}
FIDDLE
You've edited the question to include
obviously without having a loop and have a condition
but a loop and a condition is by far the most efficient and cross-browser way to do this, so why would you "obviously" not want this ?
An inefficient yet concise solution would be
var keyarr = arr.map(function(x) { return x.key } );
//keyarr is list of keys
var index=keyarr.indexOf("user_key3");
//arr[index] is your answer. Index will be -1 if the key doesn't exist
In general, finding an item that satisfies some arbitrary property in an array requires you to loop over the array:
function find(arr, name) {
for (var i=0; i<arr.length; i++) {
if ( arr[i].key === name ) {
return arr[i];
}
}
}
Then to find it,
var obj = find(arr, 'user_key3');
Using more functional solutions to find the item is fine too, but you still end up looping in some way.
However, if you are doing lookups by key, then an array of key-value pairs is not the best data structure. I would suggest using an object directly:
var map = {
'user_key1': 'user1',
'user_key2': 'user2',
'user_key3': 'user3'
}
Then lookup is simply:
map['user_key3'];
Try this - underscore.js
For Your Example -
_.where(arr, {key: "user_key3"});
You cannot do such thing with Objects in Javascript. Though here you have a combination of callbacks and loop:
arr = [{
"name": "user1",
"key": "user_key1"
},{
"name": "user3",
"key": "user_key3"
},{
"name": "user2",
"key": "user_key2"
}];
arr.forEach(function(elme){
for(var g in elme)
{
if(elme[g] == 'user_key3')
{
console.log("Found the value: "+g+" : "+elme[g]);
};
}
});