One liner to remove JS object properties with empty string [duplicate] - javascript

This question already has answers here:
How do I remove all null and empty string values from an object? [duplicate]
(13 answers)
Closed 2 years ago.
I have a JS object here
{
"test1" : "",
"test2" : "apple",
"test3" : "oranges",
"test5" : ""
}
Is there a JS one-liner that can filter out all the properties with empty strings?
Expected result:
{
"test2" : "apple",
"test3" : "oranges",
}

You can do this snippet:
const foo
const bar = Object.fromEntries(Object.entries(foo).filter(value => value[1]))
In bar you have the filtered object.
To understand this, we can split it in three steps:
With the Object.entries(foo) we got a list of foo entries. Each entry is a array with two values, the first one is a key and the second is the value.
With the filter we got all entries in the entries array in the index 1 (the values) and filter if have a value. A empty string is considered a falsie value, so by using value[1] is enough.
For last, with Object.fromEntries we got the filtered entries and we construct a object with this entries. If there is a empty string in foo, after the filter the key value combination isn't in the fromEntries param.

Try this. It will delete all empty property from your original object.
const x = {
"test1" : "",
"test2" : "apple",
"test3" : "oranges",
"test5" : ""
};
Object.keys(x).filter(k => x[k] === '').map(k => delete x[k]);
console.log(x);

You can use Object.fromEntries to rebuild a new filtered object:
var obj = {
"test1": "",
"test2": "apple",
"test3": "oranges",
"test5": ""
};
obj = Object.fromEntries(Object.keys(obj).filter(k => obj[k] !== '').map(k => [k, obj[k]]));
console.log(obj);

Related

foreach array with one key [duplicate]

This question already has answers here:
How to convert an array of objects to object with key value pairs
(6 answers)
Closed 1 year ago.
I've got an object with different values .
let arr = [{"Personal": "1000"},{"sport": "2100"},{"Industrial": "1200"},{"Commercial": "2300"},
{"Fashion": "1300"},{"Documentary": "2600"}]
How can I foreach them and then put them in an object and pick a name for them like this :
"photo_type": {
"Personal": "1000",
"sport": "2100",
"Industrial": "1200",
"Commercial": "2300",
"Fashion": "1300",
"Documentary": "2600"
}
I dont want them to be like 0 and 1 and 2.
You could create an object with Object.assign and by spreading the array.
let array = [{ Personal: "1000" }, { sport: "2100" }, { Industrial: "1200" }, { Commercial: "2300" }, { Fashion: "1300" }, { Documentary: "2600" }],
object = Object.assign({}, ...array);
console.log(object);
You can try this
const arr = [{"Personal": "1000"},{"sport": "2100"},{"Industrial": "1200"},{"Commercial": "2300"},{"Fashion": "1300"},{"Documentary": "2600"}]
let result = {}
arr.forEach(member => {result = {...result, ...member}}

Convert Array into Object of Keys and Values using javascript/jquery [duplicate]

This question already has answers here:
Converting an Array to an Object
(3 answers)
Closed 2 years ago.
I am having troubles converting an array into an object of keys and values.
Currently, I have the following nested array:
var array = [[id1, parent1, "name1", "desc1"], [id2, parent1, "name2", "desc2"], [id3, parent1, "name3", "desc3"]];
Where the length of the array is dynamic.
For my code, I require the array to be converted such that it is an object of keys and values (consisting of the first (id) and third (name) value of each nested array).
For example, the object for the above array would be as follows:
var obj = {id1: name1, id2: name2, id3: name3};
Where the id values (id1, id2, id3) would be the corresponding integer values.
I apologise if a similar question has been asked before, but I couldn't seem to find a similar question which had a solution that worked for me.
Any help or advice would be greatly appreciated!
You can use a simple for loop to do it
var array = [
["id1", "parent1", "name1", "desc1"],
["id2", "parent1", "name2", "desc2"],
["id3", "parent1", "name3", "desc3"]
];
const obj = {}
for (const item of array) {
obj[item[0]] = item[2];
}
console.log(obj);
After using Array.map to extract the first and third entries from each element in the array, you can then use Object.fromEntries to convert the extracted array of key/value pairs into an object:
const [id1, id2, id3, parent1] = [1, 2, 3, 4];
const array = [
[id1, parent1, "name1", "desc1"],
[id2, parent1, "name2", "desc2"],
[id3, parent1, "name3", "desc3"]
];
const obj = Object.fromEntries(array.map(a => [a[0], a[2]]));
console.log(obj);
You basically want to convert your original array into an array of [key, value] pairs. You can then use the Object.fromEntries function to convert those key/values into an object. So, something like this:
const arr = [
["id1", "parent1", "name1", "desc1"],
["id2", "parent2", "name2", "desc2"],
["id3", "parent3", "name3", "desc3"],
];
const results = Object.fromEntries(arr.map(x => ([x[0], x[2]])))
console.log(results)
As a good practice, it is recommended to use let or const instead of var because var "pollute" the global namespace, so that's what my example will use.
However, if you need to use var, you can replace const with var inside my example and it will still be okay.
Given the following source array:
const array = [
[id1, parent1, "name1", "desc1"],
[id2, parent1, "name2", "desc2"],
[id3, parent1, "name3", "desc3"]
];
The following block of code create an object named obj using the 1st element of the sub-array as a key, and the 3rd element as the value:
// Create an empty object
const obj = {};
// Iterate through the source array
array.forEach((element) => {
// Assign the 1st element of the sub-array as the property key
// and the 3rd element as the property value
obj[element[0]] = element[2];
});
console.log(obj);
And this has the same effect, but simpler and with a smaller footprint:
const obj = Object.fromEntries(array.map(([key, _, value]) => [key, value]));
console.log(obj);

How to convert JSON to a key-value dictionary using typescript?

I have the following json example:
{
"MyTest:": [{
"main": {
"name": "Hello"
},
"test2": {
"test3": {
"test4": "World"
},
"test5": 5
}
},
{
"main": {
"name": "Hola"
},
"test6": [{
"name": "one"
},
{
"name": "two"
}
]
}
]
}
I'm trying to convert it to an array of arrays with key-values
[[main.name: "Hello",test2.test3.test4: "World", test2.test5: 5] ,
[main.name = "Hola", test6.name: "one", test6.name: "two"] ];
Looking for some function like "is leaf" - so I will know that is the value.
Any advise for deep iteration will be very appriciated.
The flattenObject() function returns an object of one level, with the keys built from all sub keys. The recursive function checks if the current value is an object. If it is, it iterates the object with _.flatMap() and calls itself on each property with the keys collected so far. If the value is not an object, it returns an object with a single property (the joined keys), and the value.
It then merges the array of { key: value } objects to a single object.
const flattenObject = val => {
const inner = (val, keys = []) =>
_.isObject(val) ? // if it's an object or array
_.flatMap(val, (v, k) => inner(v, [...keys, k])) // iterate it and call fn with the value and the collected keys
:
{ [keys.join('.')]: val } // return the joined keys with the value
return _.merge({}, ...inner(val))
}
const obj = {"MyTest":[{"main":{"name":"Hello"},"test2":{"test3":{"test4":"World"},"test5":5}},{"main":{"name":"Hola"},"test6":[{"name":"one"},{"name":"two"}]}]}
const result = obj.MyTest.map(flattenObject)
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/lodash.js"></script>

How to create a JSON array from below JSON with key-value? [duplicate]

This question already has answers here:
How to transpose a javascript object into a key/value array
(11 answers)
How to convert an object to array of objects [duplicate]
(5 answers)
Closed 3 years ago.
Need to create below output from the JSON obj
let obj = {"id" : 1, "name": "John"};
expected result:
[
{key: "id", value: "1"},
{key: "name", value: "John"}
]
You can get the keys of obj using Object.keys() and map them to objects.
const obj = {
"id": 1,
"name": "John"
};
const result = Object.keys(obj).map(k => ({
key: k,
value: obj[k]
}));
console.log(result);
You can try this:
JSON.stringify(
Object.entries({"id" : 1, "name": "John"}).map(([key, value]) => ({
key: key,
value: value
}))
)

How can I get data iterate Json?

I need get data the my Json but I can't use 'key' because the 'key' is different each day.
I tried :
template: function(params) {
const objects = JSON.parse(JSON.stringify(params.data.masterdetail));
for (const obj of objects) {
const keys = Object.keys(obj);
const cont = 0;
keys.forEach(key => {
const valor = obj[key];
console.log('value ', valor[0]);
});
}
I first tried with 0 and then use cont, but with 0 console.log (value is undefined)....
If I use console.log ('value' , valor['name']) IT'S OK ! but I can't use keys and if I use valor[0] is undefined...........
Example Json
{
"headers": [
"headerName": "asdasd",
], //end headers
"datas": [
"idaam": "11",
"idorigen": "11",
"masterdetail": [{
"child1": {
"name": "I AM",
"age": "1"
},
"child2": {
"name": "YOU ARE",
"age": "2"
},
"child3": {
"name": "HE IS",
"age": "3"
},
}] //end masterdetail
]//end datas
}//end JSON
Edit :
I can't use 'keys' because today I receive "name", "typeval" etc. and tomorrow I can get 'surname','id' etc.
If you see in my first img you can see "4" bits of data.
1º obj[key]{
name = "adopt",
typeval= "",
etc
}
2º obj[key]{
"link" = "enlace",
"map" = "map"
etc
}
If I use this code : I get "name" OKEY but
I HAVE PROHIBITED use of value['name'] or value[typeval] because this Json always is dynamic.
var objects = params.data.masterdetail[0];
const keys = Object.keys(objects);
let value;
keys.forEach(key => {
value = objects[key];
console.log(value['name']);
console.log(value['typeval']);
});
I need for example :
var objects = params.data.masterdetail[0];
const keys = Object.keys(objects);
cont = 0 ;
keys.forEach(key => {
value = objects[key];
console.log(value[0]);
});
but value[0] is undefined and then when I arrive 2ºobj[key] link is index 0 but cont maybe is .... 4...
Sorry for my English...
To simply print the objects within the first entry in the masterdetail array, you can do the following:
var objects = params.datas.masterdetail[0];
const keys = Object.keys(objects);
keys.forEach(key => {
console.log('value ', objects[key]);
});
Based on a (suitably corrected - see my comments above) version of the JSON above, this would produce console output as follows:
value {name: "I AM", age: "1"}
value {name: "YOU ARE", age: "2"}
value {name: "HE IS", age: "3"}
Unfortunately it's not 100% clear from the question if this is the output you were looking for, but that's my best guess based on the code.
Your main mistakes were that
1) masterdetail is an array, and all the data is within the first element of that array, so to get the objects within it you need to select that element first. If the array can have multiple elements in real life then you'd need an outer loop around the code above to iterate through it.
2) If you're looping through the keys of an object, you don't need to also iterate through the properties a different way. You seemed to have two loops designed to do the same thing.

Categories

Resources