This question already has answers here:
How can I remove a specific item from an array in JavaScript?
(142 answers)
Closed 4 years ago.
{
"list": [{
"name": "car",
"status": "Good",
"time": "2018-11-02T03:26:34.350Z"
},
{
"name": "Truck",
"status": "Ok",
"time": "2018-11-02T03:27:23.038Z"
},
{
"name": "Bike",
"status": "NEW",
"time": "2018-11-02T13:08:49.175Z"
}
]
}
How do I remove just the car info from the array.
To achieve expected result, use filter option to filter out car related values
var obj = {"list":[ {"name":"car", "status":"Good", "time":"2018-11-02T03:26:34.350Z"}, {"name":"Truck", "status":"Ok", "time":"2018-11-02T03:27:23.038Z"}, {"name":"Bike", "status":"NEW", "time":"2018-11-02T13:08:49.175Z"} ]}
let result = {
list: []
}
result.list.push(obj.list.filter(v => v.name !=='car'))
console.log(result)
codepen - https://codepen.io/nagasai/pen/MzmMQp
Option 2: without using filter as requested by OP
Use simple for loop to achieve same result
var obj = {"list":[ {"name":"car", "status":"Good", "time":"2018-11-02T03:26:34.350Z"}, {"name":"Truck", "status":"Ok", "time":"2018-11-02T03:27:23.038Z"}, {"name":"Bike", "status":"NEW", "time":"2018-11-02T13:08:49.175Z"} ]}
let result = {
list: []
}
for(let i =0; i< obj.list.length; i++){
if(obj.list[i].name !== 'car' ){
result.list.push(obj.list[i])
}
}
console.log(result)
const obj = JSON.parse(jsonString);
let yourArray = obj.list;
let filteredArray = yourArray.filter(elem => elem.name !== "car");
Related
This question already has answers here:
Most efficient method to groupby on an array of objects
(58 answers)
Closed 3 years ago.
I have an array of objects that looks like this:
let stuff = [
{
"id": "48202847",
"name": "Doe"
},
{
"id": "17508",
"name": "Marie"
},
{
"id": "175796",
"name": "Robert"
},
{
"id": "175796",
"name": "Ronald"
},
]
What I want to get is a dictionary looking something like this:
{
"D": [{"id": "48202847", "name": "Doe"}],
"M": [{"id": "17508", "name": "Marie"}],
"R": [{"id": "175796", "name": "Robert"}, {"id": "175796", "name": "Ronald"}]
}
Notice how all the people whose name starts with "R" are listed under one key.
This is my function that creates a dictionary with the person's name as the key:
const byId = (array) =>
array.reduce((obj, item) => {
obj[item.name] = item
return obj
}, {})
But this obviously doesn't do what I want it to. I do have some ideas of how to make this possible, but they are extremely legacy and I would love to know how to do this right.
Any help is appreciated!
You need the first character, uppercase and an array for collecting the objects.
const byId = array =>
array.reduce((obj, item) => {
var key = item.name[0].toUpperCase(); // take first character, uppercase
obj[key] = obj[key] || []; // create array if not exists
obj[key].push(item); // push item
return obj
}, {});
let stuff = [{ id: "48202847", name: "Doe" }, { id: "17508", name: "Marie" }, { id: "175796", name: "Robert" }, { id: "175796", name: "Ronald" }],
result = byId(stuff)
console.log(result);
Here's a solution based on Set, map, reduce and filter:
let stuff = [{"id": "48202847","name": "Doe"},{"id": "17508","name": "Marie"},{"id": "175796","name": "Robert"},{"id": "175796","name": "Ronald"}];
let result = [...new Set(stuff.map(x => x.name[0]))]
.reduce((acc, val) => {
return acc = { ...acc,
[val]: stuff.filter(x => x.name.startsWith(val))
}
}, {});
console.log(result);
Great solution Nina! Could be made a little cleaner by utilizing the spread operator.
const byId = (array) =>
array.reduce((obj, item) => {
var key = item.name[0].toUpperCase();
return {
...obj,
[key]: obj[key] ? [...obj[key], item] : [item],
}
}, {});
This question already has answers here:
How to remove all duplicates from an array of objects?
(77 answers)
Closed 3 years ago.
How to remove complete record of same object in array please help me this, I am using below funtion but its only remove one value I want remove complete object of same object
var data = [{
"QuestionOid": 1,
"name": "hello",
"label": "world"
}, {
"QuestionOid": 2,
"name": "abc",
"label": "xyz"
}, {
"QuestionOid": 1,
"name": "hello",
"label": "world"
}];
function removeDumplicateValue(myArray) {
var newArray = [];
$.each(myArray, function (key, value) {
var exists = false;
$.each(newArray, function (k, val2) {
if (value.QuestionOid == val2.QuestionOid) { exists = true };
});
if (exists == false && value.QuestionOid != undefined) { newArray.push(value); }
});
return newArray;
}
I want result like this
[{
"QuestionOid": 2,
"name": "abc",
"label": "xyz"
}]
You can use reduce.
var data = [{"QuestionOid": 1,"name": "hello","label": "world"}, {"QuestionOid": 2,"name": "abc","label": "xyz"}, {"QuestionOid": 1,"name": "hello","label": "world"}];
let op = data.reduce((op,inp)=>{
if(op[inp.QuestionOid]){
op[inp.QuestionOid].count++
} else {
op[inp.QuestionOid] = {...inp,count:1}
}
return op
},{})
let final = Object.values(op).reduce((op,{count,...rest})=>{
if(count === 1){
op.push(rest)
}
return op
},[])
console.log(final)
Do with Array#filter.Filter the array matching QuestionOid value equal to 1
var data = [{ "QuestionOid": 1, "name": "hello", "label": "world" }, { "QuestionOid": 2, "name": "abc", "label": "xyz" }, { "QuestionOid": 1, "name": "hello", "label": "world" }]
var res = data.filter((a, b, c) => c.map(i => i.QuestionOid).filter(i => i == a.QuestionOid).length == 1)
console.log(res)
This question already has answers here:
Comparing two arrays of objects, and exclude the elements who match values into new array in JS
(6 answers)
Closed 5 years ago.
I want to find unique elements in a which do not exist in b on the basis of name property
EXPECTED OUTPUT
var data= [{"name":"rashffffish","color":"blue" }];
var a =[{"name":"sam","color":"red" }, {"name":"rash","color":"blue" },{"name":"rashffffish","color":"blue" }];
var b = [{"name":"sam","color":"red" },{"name":"rash","color":"red" }];
var data = [];
b.map((n)=>{
for(i=0;i<a.length;i++) {
if(n.name!= a[i].name){
data.push(a[i]);
}
}
})
console.log(data);
Use Array#filter to filter the a array and pass a predicate which uses Array#some to try to find an item. When there is no match, get those items
const a =[
{"name":"sam","color":"red" },
{"name":"rash","color":"blue" },
{"name":"rashffffish","color":"blue" }
];
const b = [
{"name":"sam","color":"red" },
{"name":"rash","color":"red" }
];
const filtered = a.filter(itemA => !b.some(itemB => itemA.name === itemB.name));
console.log(filtered);
From your code...
var a = [{
"name": "sam",
"color": "red"
}, {
"name": "rash",
"color": "blue"
}, {
"name": "rashffffish",
"color": "blue"
}];
var b = [{
"name": "sam",
"color": "red"
}, {
"name": "rash",
"color": "red"
}];
var data = a;
b.forEach((n) => {
for (i = 0; i < data.length; i++) {
if (n.name === a[i].name) {
var ind= data.indexOf(a[i]);
data.splice(ind, 1);
}
}
})
console.log(data);
This question already has answers here:
Get the index of the object inside an array, matching a condition
(16 answers)
Closed 5 years ago.
I know to find a value exist or not in an array I can use indexOf, but how to do it with an array of object?
const x = [{
"id": "roadshows",
"name": "Roadshows"
}, {
"id": "sporting_events",
"name": "Sporting Events"
}]
console.log( x.indexOf('roadshows') ) // don't work
Since this is tagged ecmascript-6, here's an ES6 array method: Array#findIndex():
const x = [{
"id": "roadshows",
"name": "Roadshows"
}, {
"id": "sporting_events",
"name": "Sporting Events"
}]
console.log( x.findIndex( o => o.id === 'roadshows' ) )
If you want a more re-useable way of doing this, consider creating a factory isId(id):
function isId(id) {
return (o) => o.id === id;
}
const x = [{
"id": "roadshows",
"name": "Roadshows"
}, {
"id": "sporting_events",
"name": "Sporting Events"
}]
console.log( x.findIndex( isId('roadshows') ) )
This is referred to as a "factory" because it is a function that returns a function with the passed parameter in its scope.
You have to loop through since you have object's inside array.
for(var i = 0; i < x.length; i++) {
if (x[i].id== 'roadshows') {
console.log(i);
break;
}
}
Or if you just checking that the object exist with that id, filter is handy
if (x.filter(function(e) x.id== 'roadshows').length > 0) {
// Yay. Do Something
}
manually I'd do something like this:
for(let item of x) {
if ( item.hasOwnProperty('id') && item['id'] == 'roadshows' ) {
//do your stuff here
}
}
And if you can use es6 and want to return the object in question, then there is always Array.prototype.find()
x.find( item => { return item.id === "roadshows" } )
// returns {id: "roadshows", name: "Roadshows"}
You have a couple of options.
First and foremost, findIndex. You pass it a function that tests if an element is what you are looking for, it returns the index of the first element that makes that function return true.
x.findIndex((o) => o.id === 'roadshows');
const x = [{
"id": "roadshows",
"name": "Roadshows"
}, {
"id": "sporting_events",
"name": "Sporting Events"
}];
console.log(x.findIndex((o) => o.id === 'roadshows'));
Another option is first mapping the relevant property to an array and searching in that one.
x.map((o) => o.id).indexOf('roadshows');
const x = [{
"id": "roadshows",
"name": "Roadshows"
}, {
"id": "sporting_events",
"name": "Sporting Events"
}];
console.log(x.map((o) => o.id).indexOf('roadshows'));
Trying to push the values into temp Array, from the existing array object. Here am validating whether the values are null or not in my existing object and then pushing it into temp Array.
But currently this is output I am getting : ["0","abc"]
Expected output should be [{"0":"abc"},{"1":"def"}]
Once the values are pushed into the temp array, I need to bind it to my html list.
This is what have tried.
JS:
var tempArray = [];
var json = [
{
"itemId": "1",
"prodTitle": "abc",
},
{
"itemId": "2",
"prodTitle": "def",
},
{
"itemId": "",
"prodTitle": "",
}
]
for (var i=0;i<json.length;i++){
if(json[i].itemId!=""&&json[i].prodTitle!="")
tempArray.itemId = json[i].itemId;
tempArray.prodTitle = json[i].prodTitle;
tempArray.push(tempArray.itemId,tempArray.prodTitle);
}
console.log(tempArray);
Demo URL
You have many mistakes, here's right one
for (var i=0; i<json.length; i++){
if(json[i].itemId && json[i].prodTitle) {
tempArray.push(json[i]);
}
}
Your mistakes
for (var i=0;i<json.length;i++){
if(json[i].itemId!=""&&json[i].prodTitle!="") // <-- mistake, braces are needed, because you have 3 lines below
tempArray.itemId = json[i].itemId; // <-- you are adding property to array
tempArray.prodTitle = json[i].prodTitle; // <-- still adding
tempArray.push(tempArray.itemId,tempArray.prodTitle); //<-- pushing strings, not valid object, use like --> {key: value}
}
Another option using Array.filter Also makes it chain-able. However a for loop will be faster, depends if the chain-ability is something you require, i find it quite powerful at times.
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
var json = [
{
"itemId": "1",
"prodTitle": "abc",
},
{
"itemId": "2",
"prodTitle": "def",
},
{
"itemId": "",
"prodTitle": "",
}
];
var tempArray = json.filter(function (item) {
return (isDefined(item.itemId) && isDefined(item.prodTitle));
});
function isDefined (o) {
return o !== undefined && o !== null && o !== '';
}
console.log(tempArray);
http://jsfiddle.net/zgg79wfa/1/
You can achieve this without jQuery by using the .filter() method:
var json = [{
"itemId": "1",
"prodTitle": "abc",
},
{
"itemId": "2",
"prodTitle": "def",
},
{
"itemId": "",
"prodTitle": "",
}];
console.log( json );
var tempArray = json.filter( function( el ) {
return el.itemId && el.prodTitle;
});
console.log( tempArray );