How to use lodash to remove keys from a JSON object?
You don't really need lodash for this. You can look at each key in your data and the just pull the values from each element of the array and concat it into a new array.
const data = {"north": [{"2018-07-01": {"date": "2018-07-01","name": "david","age": 11},"2018-07-02": {"date": "2018-07-02","name": "damo","age": 16},"2018-07-03": {"date": "2018-07-03","name": "dani","age": 12}}],"south": [{"2018-07-01": [{"fruit": "banana","date": "2018-07-01","name": "miller","age": 11},{"fruit": "mango","date": "2018-07-01","name": "mano","age": 11},{"fruit": "avocado","date": "2018-07-01","name": "karl","age": 14}],"2018-07-02": [{"fruit": "pineaplle","date": "2018-07-02","name": "gautier","age": 12},{"fruit": "apple","date": "2018-07-02","name": "gauteng","age": 9},{"fruit": "watermelon","date": "2018-07-02","name": "garzier","age": 12}]}]};
Object.keys(data).forEach(k => { data[k] = data[k].reduce((a, c) => a.concat(...Object.values(c)), [])})console.log(data)
Removing object properties with Lodash
Get a list of properties from model
using _.keys()
, and use _.pick()
to extract the properties from credentials
to a new object:
var model = {
fname:null,
lname:null
};
var credentials = {
fname:"xyz",
lname:"abc",
age:23
};
var result = _.pick(credentials, _.keys(model));
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js"></script>
Lodash remove items recursively
_.transform()
the object to another object, and while passing the values to the new object, check if the value is an object and if it has the 'reach' property, and if so use _.omit()
to get a new object without reach
:
var obj = { total: 350, SN1: { reach: 200, engagementRate: 1.35 }, SN2: { reach: 150, engagementRate: 1.19 }};
var result = _.transform(obj, function(result, value, key) { result[key] = _.isObject(value) && `reach` in value ? _.omit(value, 'reach') : value;});
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
remove JSON key value, if the value inside the object exists before
Update: OP doesn't care about keys, so to just remove duplicate
values, and then of course the associated key, below is an example
using Set's.
Updated working snippet below ->
const data = {"modelhelloamazingIssue":{"modelhelloamazingIssueSevere":{"nameText":"Name","helloAnalysisType":["Normal","Mild","Moderate","Severe"],"helloText":"hello","abouthellosolo":"hello solo is a serious hello disorder that causes you to stop amazing during hello. It's important to understand the signs and symptoms.","noteText":"This is not a medical diagnosis and you may want to talk to your doctor.","buttonText0":"Next steps"},"modelhelloamazingIssueMild":{"nameText":"Name Example","helloAnalysisType":["Normal","Mild","Moderate","Severe"],"helloText":"hello","abouthellosolo":"My god this is so cool.","noteText":"This is not a medical diagnosis and you may want to talk to your doctor.","buttonText1":"Next steps"}}};
function removeDuplicateValues(obj) {
const dups = new Set();
function inner(o) {
const needSplice = [];
for (const [k, v] of Object.entries(o)) {
if (typeof v === 'object') {
inner(v);
if (!Object.keys(v).length) delete(o[k]);
} else {
if (dups.has(v)) {
if (Array.isArray(o)) needSplice.unshift(k);
else delete o[k];
}
else dups.add(v);
}
}
for (const i of needSplice) o.splice(i, 1);
}
inner(obj);
}
removeDuplicateValues(data);
console.log(data);
lodash remove object from
You can use _.remove inside an forEach using an object as the predicate:
_.forEach(obj.products, function(product) {
_.remove(product.comments, {id_comment: 1});
});
If an object is provided for predicate the created _.matches style callback returns true for elements that have the properties of the given object, else false.
var obj = { id_order: '123123asdasd', products: [{ description: 'Product 1 description', comments: [{ id_comment: 1, text: 'comment1' }, { id_comment: 2, text: 'comment2' }] }, { description: 'Product 2 description', comments: [{ id_comment: 2, text: 'comment2' }, { id_comment: 3, text: 'comment3' }] }, { description: 'Product 3 description', comments: [{ id_comment: 1, text: 'comment1' }, { id_comment: 2, text: 'comment2' }] }]};
_.forEach(obj.products, function(product) { _.remove(product.comments, {id_comment: 1});});
document.getElementById('result').innerHTML = JSON.stringify(obj, null, 2);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.10.1/lodash.min.js"></script><pre id="result"></pre>
How to remove empty object from JSON recursively using lodash
You can _.transform()
the object recursively to a new one, and clean empty objects and arrays on the way.
Note: I've added more elements to the structure for demonstration
var template = { personal: {}, education: {}, certificate: [{}, {"test": "Test"}, {}, {}, [{}], [{}, 1, []]], experience: [[1, 2, [], { 3: [] }]]};
function clean(el) { function internalClean(el) { return _.transform(el, function(result, value, key) { var isCollection = _.isObject(value); var cleaned = isCollection ? internalClean(value) : value;
if (isCollection && _.isEmpty(cleaned)) { return; }
_.isArray(result) ? result.push(cleaned) : (result[key] = cleaned); }); }
return _.isObject(el) ? internalClean(el) : el;}
console.log(clean(template));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>
Removing key in a JSON object but want to keep the original
You can use map and spread operator like below
let a = [ { firstName: 'Tony', lastName: 'Stack' }, { firstName: 'Iron', lastName: 'Man' } ]; let removed = a.map(({firstName, ...lastName}) => lastName);
console.log('before:',a)console.log('after:', removed)
Related Topics
Create a Newline for Every X Number of Characters
How to Detect Overflow of React Component Without Reactdom
Angular:Onclick on HTML Element According to Its Class
Get High-Order Block'S Id on Click
How to Add Spaces to for Loop Output in JavaScript
How to Compare Two Arrays Using Lodash (The Order Matters)
How to Get Route Url Params in a Page in Nuxt2 and 3
Invalid Attempt to Spread Non-Iterable Instance
How to Implement Ping/Pong Request for Websocket Connection Alive in JavaScript
Multiply and Sum Input Values Created Dynamically in Jquery
How to Increment a Number After Every 1 Second Using JavaScript
Generate a Weighted Random Number
Html Anchor Tag With JavaScript Onclick Event
How to Update Component State on Redux State Change
Pass a String With Double and Single Quotes as Parameter to JavaScript Function
Javascript Add Class Active When Click a Link After Load Another Page
How to Call the Same Method for Different Elements With Different Ids