First show the object that is equal to the incoming variable [duplicate] - javascript

This question already has answers here:
Sort array of objects by string property value
(57 answers)
Closed 9 months ago.
I have an object that looks like the example below. I want the object that is equal to the id in the variable to be sorted first. How can I do that?
const id = 15;
const obje = [
{
"name": "Join",
"phone": "1234",
"email": "test#mysite.com",
"id": "12"
},
{
"name": "Join2",
"phone": "4321",
"email": "test2#mysite.com",
"id": "15"
}
]
What I want to do is to rank the object equal to the id in the variable to the top.
Thanks for your help in advance 🙏🏻

Instead of sorting find the index of the object where its id matches the search id, then splice it out, and then add it to the start of the array with unshift. You are mutating the array but it's quick, and without knowing the complete structure of your array, probably the easiest approach.
const id=15,arr=[{name:"Join",phone:"1234",email:"test#mysite.com",id:"12"},{name:"Join2",phone:"4321",email:"test2#mysite.com",id:"15"}];
const index = arr.findIndex(obj => obj.id === id);
arr.unshift(arr.splice(index, 1)[0]);
console.log(arr);

Related

How to remove an object from array based on value in javascript [duplicate]

This question already has answers here:
How to filter object array based on attributes?
(21 answers)
Closed 2 years ago.
I have an array of object, I want to remove entire object from the array whose value is 1, I am using filter but not working. Here is the code:
var arraydata = [
{"name":"name1","value":1},
{"name":"name2","value":2},
{"name":"name3","value":3}
];
arraydata.filter(i=>i.value !== 1);
console.log(arraydata);
.filter return a new array rather than mutating the current one. So you should reassign arraydata
var arraydata = [{
"name": "name1",
"value": 1
}, {
"name": "name2",
"value": 2
}, {
"name": "name3",
"value": 3
}];
arraydata = arraydata.filter(i => i.value !== 1);
console.log(arraydata);
You almost had it:
let arraydata = [{"name":"name1","value":1},{"name":"name2","value":2},{"name":"name3","value":3}];
const after = arraydata.filter(x=>x.value !== 1);
console.log('before',arraydata,'after',after);
arraydata = after;
note: it is better not to use i for the item in the filter (it is not an error, but may cause confusion when you want to filter by content and by index)

Remove one key from array in Javascript [duplicate]

This question already has answers here:
How can I remove a specific item from an array in JavaScript?
(142 answers)
Closed 2 years ago.
I have an object 'myObjects':
let myObjects = {
"obj1":["X1","1.2"],
"obj2": "2",
"obj3": "3"
};
I am trying to only remove the X1 from the obj1 section. I have tried doing:
delete obj1[0];
however end up with
[null,"1.2"]
how do I get rid of the null?
You are going to remove element from Array not Object. In that case, you can use Array.splice as follows.
let myObjects = {
"obj1":["X1","1.2"],
"obj2": "2",
"obj3": "3"
};
delete myObjects.obj1.splice(0, 1);
console.log(myObjects);

Parsing JSON keys into array of strings [duplicate]

This question already has answers here:
Get array of object's keys
(8 answers)
Closed 4 years ago.
I am currently trying to handle a GET request that returns a body in application/json structured like this:
{
"items": {
"item001": {"id":1234, "name": "name001"},
"item002": {"id":1235, "name": "name002"},
"item003": {"id":1236, "name": "name003"}
}
}
I'm trying to get an array of strings that looks like
array = ["item001", "item002", "item003"];
I don't care about any of the underlying hierarchy, I just need the key of each object as an array. I've tried several different methods (map(), JSON.stringify(), etc) but I can't seem to index each key in a array[i] format.
In fact, each time I try to even print the name of a single key, for example
var obj = JSON.parse({'whole json here'});
print(obj.items[1]);
I get an [object Object] error, which makes sense as obj.items is not indexed with a key other than "item001" for example. However, I do not know what the key for each object will be, hence the need for an array of the keys. Thank you in advance!
You can do Object.keys.It will return an array of the keys of an object
var x = {
"items": {
"item001": {
"id": 1234,
"name": "name001"
},
"item002": {
"id": 1235,
"name": "name002"
},
"item003": {
"id": 1236,
"name": "name003"
}
}
}
var y = Object.keys(x.items);
console.log(y)
You can use Object.keys(). For Reference
var obj={"items":{"item001":{"id":1234,"name":"name001"},"item002":{"id":1235,"name":"name002"},"item003":{"id":1236,"name":"name003"}}};
var result = Object.keys(obj.items);
console.log(result);
Object.keys will do that.
var obj = JSON.parse({'your json'});
console.log( Object.keys(obj.items) );

How to retrieve an specific value from a JSON involving multiple key value pairs using Javascript array [duplicate]

This question already has answers here:
Find object by id in an array of JavaScript objects
(36 answers)
How to find object in array by property in javascript?
(3 answers)
Closed 5 years ago.
I have following json
var dictionary = [{"key":"Math","value":"20"},{"key":"History","value":"10"},{"key":"Chemistry","value":"12"}]
I can access for instance the second element of the array like this:
dictionary[1].value
it returns 10 which is the score of the History subject.
What I'm looking for is the way so that I can access it by the word "History" itself, I mean I need a code like this:
dictionary["History"].value
How can I achieve that?
Ok, so here is a hack. You can use Array as an Object and insert any key you want. You can apply forEach to it and bind keys with properties like below.
var dictionary = [{"key":"Math","value":"20"},{"key":"History","value":"10"},{"key":"Chemistry","value":"12"}]
dictionary.forEach(function(item) {
dictionary[item.key] = item;
});
console.log(dictionary["History"].value);
Note: This is just a Hack and will fail in case of duplicate entries.
Edited
Solution in case of duplicate keys
var dictionary = [{
"key": "Math",
"value": "20"
}, {
"key": "History",
"value": "10"
}, {
"key": "Chemistry",
"value": "12"
}, {
"key": "Chemistry",
"value": "13"
}]
dictionary.forEach(function(item) {
if (dictionary[item.key] && !Array.isArray(dictionary[item.key])) {
dictionary[item.key] = [dictionary[item.key]];
dictionary[item.key].push(item);
} else if (dictionary[item.key] && Array.isArray(dictionary[item.key])) {
dictionary[item.key].push(item);
} else {
dictionary[item.key] = item;
}
});
console.log(dictionary["Chemistry"]);
By using find() to iterate over your array.
From MDN Array.prototype.find():
The find() method returns the value of the first element in the array that satisfies the provided testing function. Otherwise undefined is returned.
const dictionary = [{"key":"Math","value":"20"},{"key":"History","value":"10"},{"key":"Chemistry","value":"12"}]
const result = dictionary.find(item => {
// if this returns `true` then the currently
// iterated item is the one found
return item.key === 'History'
})
console.log(result)
There's more than one way to do this but this one is the most straightforward and succinct.
Try this:
var dictionary = [
{"key":"Math","value":"20"},
{"key":"History","value":"10"},
{"key":"Chemistry","value":"12"}
];
function getValue(searchKey) {
var retVal;
dictionary.some(item => {
if (item.key === searchKey) {
retVal = item.value;
return true;
}
});
return retVal;
}
console.log(getValue('History'));
If goes through your array of objects and finds the object that matches its key to your searchKey and returns the result.
Or you can convert your array of objects into a single object and then reference it directly:
var dictionary = {};
[
{"key":"Math","value":"20"},
{"key":"History","value":"10"},
{"key":"Chemistry","value":"12"}
].forEach(item => {dictionary[item.key] = item.value;});
console.log(dictionary.History);

Sorting an Object in javascript Firefox vs Chrome [duplicate]

This question already has answers here:
Sort JavaScript object by key
(37 answers)
Sorting object property by values
(44 answers)
Closed 9 years ago.
I have an object that looks like:
{
"2013": {
"name": 2013,
"ts_create": 1375254000000,
"view_url": "some_url",
"save_url": "some_url_2",
"id": "",
"exists": true,
"children": []
},
"2012": {
"name": 2013,
"ts_create": 1375254000000,
"view_url": "some_url",
"save_url": "some_url_2",
"id": "",
"exists": true,
"children": []
},
"2011": {
"name": 2013,
"ts_create": 1375254000000,
"view_url": "some_url",
"save_url": "some_url_2",
"id": "",
"exists": true,
"children": []
}
}
The problem I am facing is, it seems only in Google Chrome that when I loop over this object the objects loop backwards.
The expected result of looping over and displaying the object should list out things from 2013, 2012, 2011. Which happens in Firefox.. However no change in the method, same exact object in Chrome.. I will get 2011, 2012, 2013
So with this I need to obviously apply some level of sorting over this object before looping over it, seeing as Chrome wants to get the loop to read over it backwards. Problem I am facing with that is not entirely sure how to sort an object with JS
Instead of property/value pair implement this structure as an array of objects. Arrays you can sort by any property of objects it contains.
Because objects are unordered collections, it's up to you to enforce the ordering you want.
One way is to get an Array of the object properties, sort them, then iterate the Array.
Object.keys(data)
.sort(function(a, b) {
return +b - +a;
})
.forEach(function(key) {
var item = data[key];
});
This assumes that you wanted a simple descending order.
When you iterate over object properties, there is no guarantee on the order. You can add your objects to an array, and sort the array instead:
var obj = {"2012" : {}, "2011" : {}, "2013" : {}};
var arr = [];
for (var year in obj) {
arr.push({year : year, data : obj[year]});
}
arr.sort(function(a,b) {
return b.year - a.year;
});
http://jsfiddle.net/wK5KE/
One way to get the keys in sorted order would be to use the method defined here to generate an array of the keys:
Getting JavaScript object key list
Then you could use the javascript sort function:
http://www.w3schools.com/jsref/jsref_sort.asp
Or write your own if you feel inclined.
Then just loop through the array of keys, using object[key] to extract the value.

Categories