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

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"}

Related

Store certain values in JSON into parameters in React

brand new to Javascript.
I have figured out how to get data back from a Monday.com board, and it is returned as a JSON value like this:
{
"boards": [
{
"items": [
{
"column_values": [
{
"id": "location",
"title": "Location",
"type": "location",
"text": "Cape Town, South Africa"
}
]
},
{
"column_values": [
{
"id": "location",
"title": "Location",
"type": "location",
"text": "Paris, France"
}
]
},
{
"column_values": [
{
"id": "location",
"title": "Location",
"type": "location",
"text": "New York, NY, USA"
}
]
}
]
}
]
}
There are 3 items here, but this amount can be anything.
I need to get the location text (e.g. "Cape Town, South Africa") and then I need to use this later in an API call to get the weather of this location.
I finally managed to display in the console the location, like this:
console.log(JSON.stringify(this.state.boardData.boards[0].items[0].column_values[0].text));
Obviously this then displays what I want, but only the value of the first item.
I need to do this dynamically to get all the locations, and I need to store this into variables, so that I can then make an API call to get the weather of each of the 3 (or more) locations.
I am totally lost and have been struggling for hours. Once I manage to do this, I still have no idea how I'll make the API call but one thing at a time :)
Another approach:
const rawData = {boards:[{items:[{column_values:[{id:"location",title:"Location",type:"location",text:"Cape Town, South Africa"}]},{column_values:[{id:"location",title:"Location",type:"location",text:"Paris, France"}]},{column_values:[{id:"location",title:"Location",type:"location",text:"New York, NY, USA"}]}]}]};
const locations = [];
for (const board of rawData.boards) {
for (const item of board.items) {
for (const value of item.column_values) {
locations.push(value.text);
}
}
}
console.log(locations);
You can extract the text with some amount of nested .map. Map boards => map items => map column_values. You will get an array of arrays of arrays. And then you can apply .flat() to unwrap them all. (.flat(Infinity); also can be used)
const apiData={boards:[{items:[{column_values:[{id:"location",title:"Location",type:"location",text:"Cape Town, South Africa"}]},{column_values:[{id:"location",title:"Location",type:"location",text:"Paris, France"}]},{column_values:[{id:"location",title:"Location",type:"location",text:"New York, NY, USA"}]}]}]};
const locations = apiData.boards
.map((board) => board.items.map((i) => i.column_values.map((cv) => cv.text)))
.flat(2);
console.log(locations);
So in javascript we have an array function map, using which we can iterate over array that can be used here. It would look something like this:
let arr = boards[0].items.map(element => element.column_values[0].text)
and this arr will contain the list of all the city names, which you can further use to send the data to api.
(Edit: considering column_values to be array with one element only and items can have multiple elements)

How can I insert each object into key pair value

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.

Need to understand JavaScript arrays, objects, and properties

First see how JSON should look like
[
{"ShortCode":"US","Name":"United States"},
{"ShortCode":"CA","Name":"Canada"},
{"ShortCode":"AG","Name":"Antigua and/or Barbuda"}
]
Code:
var countries = [];
map = {};
// This is going to make an HTTP post request to the controller
return $.post('/Client/CountryLookup', { query: query }, function (data) {
// Loop through and push to the array
$.each(data, function (i, country) {
map[country.Name] = country;
countries.push(country.Name);
});
$post() will return the above json & i need to parse the json in each loop
but i do not understand what will be store in map object this line map[country.Name] = country;
Suppose country name is "united state" so actually store will be map['united state']=country what does it mean?
Even in the save code map{} access later like
var selectedShortCode = map[item].ShortCode;
How map can have a property like ShortCode ??
So please discuss this type of coding technique in detail and help me to understand the above code with few more example. thanks
your map is an object literal defined also known as hash or dictionary or relational array in other languages what basically relates a key(Strin) with a value(anything) in this case relates country names with the actual country object thats why
the map structure after your map[country.Name] = country operations would be
{
"United States":{"ShortCode":"US","Name":"United States"},
"Canada":{"ShortCode":"CA","Name":"Canada"},
"Antigua and/or Barbuda":{"ShortCode":"AG","Name":"Antigua and/or Barbuda"}
}
then when you do
map["United States"]
you get
{"ShortCode":"US","Name":"United States"}
Your data after the $.post call would be:
data =
[
{ ShortCode: "US", Name: "United States" },
{ ShortCode: "CA", Name: "Canada" },
{ ShortCode: "AG", Name: "Antigua and/or Barbuda" }
];
Take a look at the jQuery's .each function documentation.
It basically can be rewritten as follows:
for(var i in data)
{
var country = data[i];
map[country.Name] = country;
countries.push(country.Name);
}
So you end up with:
map =
{
"United States": { ShortCode: "US", Name: "United States" },
"Canada": { ShortCode: "CA", Name: "Canada" },
"Antigua and/or Barbuda": { ShortCode: "AG", Name: "Antigua and/or Barbuda" }
};
countries = [ "United States", "Canada", "Antigua and/or Barbuda" ];
So your code parses json, and outputs all the countries that exist (countries) and all the data associated with them (map), in two different objects. countries can be used to easily itterate through the map, but there's no real need for it.
EDIT:
var country = data[0];
// country = { ShortCode: "US", Name: "United States" };
map[country.Name] = country;
// map["United States"] = { ShortCode: "US", Name: "United States" };
So you can later take map["United States"], it will return you an object { ShortCode: "US", Name: "United States" }, then you can simply access it's property ShortCode if you'd like to.
Mind that all variables in JavaScript are passed by reference, and that myObject["someProperty"] is exactly the same as myObject.someProperty.

Iterating data to get value

I have following loop
for (var i in data) {
console.log(data[i])
}
Data that I for loop is iterating through is
"data": [
{
"MainArea": "North West"
},
{
"MainArea": "South West"
},
When I run it I get following output in firebug
[Object { MainArea="North West"},
Object { MainArea="South West"}]
What I am trying to get is just the value of it. So that when I tried
console.log(data[i].MainArea)
Hoping to get just the "North West" and South West" values, instead
I get "undefined" in my console.
Try following:
console.log(data[i].MainArea);
You are trying to get information out of objects property. Since your variables enclosed to json format list you can reach your variables through named properties.
UPDATE: According your addition to the your original question I created DEMO.
var myObj = {"data": [
{
"MainArea": "North West"
},
{
"MainArea": "South West"
},
],
},
data = myObj['data'],
data_length=data.length;
for (var i= 0; i < data_length; i++)
{
console.log(data[i].MainArea);
}
Keep in mind that when you are iterating key value pairs you should use for ... in loop while when you are iterating through array you should use for loop. For example if your data property contains sorted array, for ... in loop will not guaranty to loop from array item 0 to N. It means it will not follow sequence. So use only for loops for array and for ... in for non-array objects. Read about this in here. Some jsPerf comparison be seen here.
The problem is the data object you are iterating has another property called data which is an array containing the target objects, and of course the property key you need to use is MainArea so try
var data = {
"data": [{
"MainArea": "North West"
}, {
"MainArea": "South West"
}]
}
for (var i in data.data) {
console.log(data.data[i].MainArea)
}
Demo: Fiddle
The object is defined as this:
{ MainArea="North West" }
So it has only one property, called MainArea. There's no property called value so of course value is undefined. Try:
console.log(data[i].MainArea)

How to get json object key name from collection and iterate

Below is my json structure. On success of collection.fetch() i'm looping through the structure.
Currently i use
this.collection.each(function(model) { .. }
How do i obtain key name like plants, animals and instead loop using the names.
JSON
var jsonObj = { // 0 - recommended , 1 - New
"plants" : [
{
"title" : "title1",
"desc": "description.."
},
{
"title" : "titl2",
"desc": "description."
}
],
"animals" : [
{
"title" : "title1",
"desc": "description.."
},
{
"title" : "titl2",
"desc": "description."
}
]
};
Snapshot of collection
This would work, but you'd use a normal for loop, not "each":
for(i in jsonObj){
alert(i);
}
here is a fjsfiddle: http://jsfiddle.net/r5nwP/
Is that what you're after?
You can use the underscore keys to get a list of names:
var thenames =_.keys(yourobject);
In this case thenames will contain a list of the keys you are looking for. Here is the documentation for it:
http://underscorejs.org/#keys
keys_.keys(object)
Retrieve all the names of the object's properties.
_.keys({one : 1, two : 2, three : 3});
=> ["one", "two", "three"]

Categories