How can I insert each object into key pair value - javascript

I have a object like
where I declear some properties and value.
var obj = {
"country" : "USA",
"CApital" : "WDC",
"President" : "Trump"
}
Now I am adding in this way, I make one id and in that id I want to add my object property and values.
var myId = obj.President;
this.newObj[myId] = {};
Object.each(obj, function(key, value) {
this.newObj[myId][key] = value;
});
My output shoud be
obj :{
Trump :{
"country" : "USA",
"CApital" : "WDC",
"President" : "Trump"
}
}

There is no such thing as Object.each.
Simplest is use Object.assign() to merge copy of original object to new object
let obj = {
"country" : "USA",
"CApital" : "WDC",
"President" : "Trump"
}
let newObj= {[obj.President] : Object.assign({}, obj)}
console.log(newObj)

I understood you want to create a new object with a property value equals to source object identifier evaluation, and inside that property goes the initial object. Something like this:
const obj = {
country: 'usa',
capital: 'dc',
president: 'trump'
};
function myPropAndObjectValues(obj, prop) {
return {
[obj[prop]]: {...obj}
};
}
console.log(myPropAndObjectValues(obj, 'president'));
Pd. Object.each doesn't exist.

Related

How to get the object property and its property value if the property value is not null then transform the object property?

I have an object here that I want to get the property and property value if the the property value is not null.
var sample = {code: null, area: "Tokyo", contact: null, name: "John Doe", schedule:"Aug 29, 2021"}
Then transform the object property into
"area" into "location"
"name" into "fullName"
"schedule" into "date"
Is there a way to do it?
Thanks!
const removeNull = (sample) => {
let newObj = {}
for (var key in sample) {
if (sample[key]) {
newObj[key] = sample[key]
}
}
return newObj;
}
let sample = {code: null, area: "Tokyo", contact: null, name: "John Doe", schedule:"Aug 29, 2021"}
console.log(removeNull(sample))

Convert arrays to key value pair

I have an array
[
{"field" : "flight1", "value" : "123"},
{"field" : "flight2", "value" : "456"}
]
is it possible to become key value pair?
{
"flight1" : "123",
"flight2" : "456"
}
You can use reduce() and return object as result.
var arr = [{"field" : "flight1", "value" : "123"},{"field" : "flight2", "value" : "456"}]
var result = arr.reduce(function(r, e) {
r[e.field] = e.value;
return r;
}, {});
console.log(result)
The new Map() constructor can do this for you:
var data = [
{"field": "flight1", "value": "123"},
{"field": "flight2", "value": "456"}
];
var result = new Map(data.map(obj => [obj.field, obj.value]));
If you're not familiar with Map objects, they work almost exactly the same as plain objects, except they are a little easier to iterate over, and have a .size property.
But if you prefer to have a plain object, you can get one this way:
var result = Object.fromEntries(data.map(obj => [obj.field, obj.value]));
You could map the key value pair and assign it to an object.
var data = [{ field: "flight1", value: "123" }, { field: "flight2", value: "456" }],
result = Object.assign(...data.map(a => ({ [a.field]: a.value })));
console.log(result);
you could use a standard for loop:-
var data = [{"field" : "flight1", "value" : "123"},{"field" : "flight2", "value" : "456"}];
var obj = {};
for (var i = 0; i < data.length; i++)
obj[data[i].field] = data[i].value;
console.log(obj);
This might help someone another day. I tried all the examples above, but each time the console was giving me something like this:
{
flight1: "123",
flight2: "456"
}
My problem was that I was converting a serialized array way to soon which resulted in lots of tiny problems. Below was the code that didn't work:
var data = $('#myform').serializeArray();
data = JSON.stringify(data);
data,result = Object.assign(...data.map(a => ({ [a.name]: a.value })));
database.addUser(result);
Note that flight1 and flight2 lost their double quotes. Below was my solution:
var data = $('#myform').serializeArray();
data,result = Object.assign(...data.map(a => ({ [a.name]: a.value }))); //result was already turned into a JSON array
database.addUser(result);
NB: This was a code for submitting user information to a database (neDB) using the electron framework

Mapping out JSON structure

I'm parsing a JSON message which looks something like:
{
staff : [
{name : 'John', department : 'Math'},
{name : 'Sally', department : 'Science'},
],
students : [
{name : 'Bob', department : 'Law'},
{name : 'Lisa', department : 'IT'}
]
}
From which I'd like to pull out an array of each separate value.
i.e.
names -> ['John', 'Sally', 'Bob', 'Lisa']
At the moment I'm doing something like
var names = [];
msg.staff.forEach(function(e) { names.push(e.name) })
msg.students.forEach(function(e) { names.push(e.name)})
This feels overly verbose, just wondering if there's a cleaner way to approach this (for every attribute). I'm already including lodash in this project.
You can use _.pluck to get the value of a property of each object in an array:
_.pluck(obj.staff.concat(obj.students), 'name')
Your instinct is right; you don't need a mutable array to do this with lodash.
_(obj).map().flatten().pluck('name').value();
This version works for any number of array values in o.
JSBin
Edit missed that you had lodash available, will leave this vanilla JS version here anyway.
You could use map to be more concise:
var directory = {
staff : [
{name : 'John', department : 'Math'},
{name : 'Sally', department : 'Science'},
],
students : [
{name : 'Bob', department : 'Law'},
{name : 'Lisa', department : 'IT'}
]
};
var names = directory.staff.concat(directory.students).map(function(person) {
return person.name;
});
If you don't know the individual key names before hand, you could do:
Object.keys(directory).map(function(key) {
return directory[key]
}).reduce(function(p,c){
return p.concat(c)
}).map(function(person) {
return person.name;
});
I didn't catch the requirement of getting an array of all values stored under each key, this should do it though:
Object.keys(directory).map(function(key) {
return directory[key];
}).reduce(function(p,c) {
return p.concat(c);
}).reduce(function(p, c) {
Object.keys(c).forEach(function(oKey) {
if(p[oKey]) p[oKey].push(c[oKey]);
else p[oKey] = [c[oKey]];
});
return p;
}, {});
This returns the following:
{
"name":["John","Sally","Bob","Lisa"],
"department": ["Math","Science","Law","IT"]
}

How to remove all elements with the same key in JavaScript object

I am working with JSON data in a JavaScript object like this:
var data = [
{ "City" : "New York", "State" : "New York" },
{ "City" : "Fargo", "State" : "North Dakota" },
{ "City" : "Los Angeles", "State" : "California" }
];
And I want to remove state data so it ends up like this:
var data = [
{ "City" : "New York"},
{ "City" : "Fargo"},
{ "City" : "Los Angeles"}
];
Currently I'm looping through and removing it but is there a way to remove the city from the object without having to loop through?
I found the "delete" operator ("The delete operator removes a property from an object.") but it seems to only work if there is just one item with that property, not globally as in the example object.
delete object["State"] //doesn't work
Edit: My bad. I copy/pasted and edited incorrectly. I have changed the original post to use correct format as supplied in Mr. Polywhirl's answer.
Edit: I ended up using the map method as suggested by mccainz. Using map allows for pulling all of a certain key/value pair (like city) from one array into another. You can also pull multiple like
newData = data
.map(function(v){
return {City:v.City, State:v.State};
});
It will work for my purposes and is better since I'm keeping the minority of the key/value pairs. However, it doesn't appear that there are any solutions for performing the task in the original question. For example, if you had 100 different key/value pairs per array item, you'd have to add 99 to a new array instead of being able to just remove one from the existing.
You should convert your data to an array of objects and simply operate on the array. The example below uses array.map to return an array with the State properties absent. However, there are numerous ways to skin this cat.
(edited to demonstrate a filtering preprocess before the map)
var data=[];
data.push({"City":"New York","State":"New York"});
data.push({"City":"Fargo","State":"North Dakota"});
data.push({"City":"Los Angeles","State":"California"});
var newData;
newData = data
.filter(function(v){
return v.State !=='California';
})
.map(function(v){
return {City:v.City};
});
Array.prototype.filter
Array.prototype.map
As others have indicated, you can't have duplicate properties in your JSON object. Your data is meant to be in an Array, not in one monster object.
If you don't want to modify the original object, you can combine map and reduce to create filtered objects.
var data = [
{ "City" : "New York", "State" : "New York" },
{ "City" : "Fargo", "State" : "North Dakota" },
{ "City" : "Los Angeles", "State" : "California" }
];
var filterKeys = function(data, keysToFilter) {
return data.map(function(item) {
return Object.keys(item).reduce(function(result, key) {
if (keysToFilter.indexOf(key) === -1) result[key] = item[key];
return result;
}, {});
});
}
document.body.innerHTML = JSON.stringify(filterKeys(data, ['State']), null, ' ');
body {
font-family: monospace;
white-space: pre;
}
Result
[
{ "City": "New York" },
{ "City": "Fargo" },
{ "City": "Los Angeles" }
]
you cant initiate an object with two identical keys.for example
var obj={city:"NEW YORK",city:"NEW JERSEY"}
city property will hold NEW JERSEY.because it's overwritten.
JSON.stringify(obj); // {"city":"NEW JERSEY"}
if you initiate an object with your json.your obj1 will hold only one city and state property.
JSON.stringify(obj1); //{"City":"Fargo","State":"North Dakota"}

Javascript, deep extend

So I have an object I'm trynig to deep extend into - right now the extend function works if the lowest level is just an array, So it looks like this :
function(base, next) {
var dataEntry = base.filter(function(it) {
return it.module === next.module;
})[0];
if (dataEntry) {
var diff = next.customUrl.filter(function(it) {
return dataEntry.customUrl.indexOf(it) === -1;
});
dataEntry.customUrl = dataEntry.customUrl.concat(diff).sort();
//_.extend(dataEntry, next);
} else {
base.push(next);
}
}
And this works if the object looks like :
[
{"name" : "one", "test" : ["1","2"]},
{"name" : "two", "test" : ["1","2"]}
]
However some things had to change and now the object looks like this :
[
{"name" : "one", "test" : [{"random1" : true},{"random2" : false}] },
{"name" : "two", "test" : [{"random3" : true},{"random4" : false}]}
]
Where the keys in the array is now an array of objects, and the objects keys are random. So If there was an object with the same key - replace the value (unless its the same, otherwise push a new object inside of there.
So for that object above I would pass this to merge into it for example:
{"name" : "one", "test" : [{"random2" : true}]}
So that would change the value of random2 to true, or something like this
{"name" : "one", "test" : [{"random18" : true}] }
where that would push in random 18 like so :
[
{"name" : "one", "test" : [{"random1" : true},{"random2" : false},{"random18" : true}] },
{"name" : "two", "test" : [{"random3" : true},{"random4" : false}]}
]
Unsure how to traverse deeper and merge. Thanks for reading!!
Edit : first stab at it -
function(base, next) {
var dataEntry = base.filter(function(it) {
return it.module === next.module;
})[0];
if (dataEntry) {
var allTags = [];
allTags.push.apply(allTags, dataEntry.customUrl);
allTags.push.apply(allTags, next.customUrl);
dataEntry.customUrl = allTags;
} else {
base.push(next);
}
}
Does not work because it does not cover over objects if they are the same, just pushes into array.
http://jsfiddle.net/p08ayvv8/
this fiddle shows you how jQuery can deal with (deep) extending objects.
See http://api.jquery.com/jquery.extend/ for a detailed explaination.
It is mentionable though that when preforming the second extension jQuery will prepend the old value of test to the array, thats why I added
o1.test = o1.test[0];

Categories