Angular 7, create new object with some values from object - javascript

I have object like this
const Obj =
"Value1": {
"value1value": "1"
},
"Value2": {
"value2value": "2"
},
"Value3": {
"value3value": "3"
},
"BTest": {
"1": "1",
"2": "2"
},
"Value4": {
"value4value": "value4value"
},
"ATest": {
"1": "1",
"2": "2"
},
"Value5": {
"value5value": "value5value",
"value6value": "value6value"
},
"TestA": {
"1": "1",
"2": "2"
};
What i need is to create new object that will look like this
cont newObject =
"Value1": {
"value1value": "1"
},
"Value2": {
"value2value": "2"
},
"Value3": {
"value3value": "3"
},
"Value4": {
"value4value": "value4value"
},
"Value5": {
"value5value": "value5value",
"value6value": "value6value"
};
Some values are removed, i have tried with like
const newObject = Obj.map(o => {
return { };
});
But i had no luck, does somebody knows what has to be done, thanks in advance

Looks like you want to extract keys which starts with specific value so you can do something like
var obj={"Value1": {
"value1value": "1"
},
"Value2": {
"value2value": "2"
},
"Value3": {
"value3value": "3"
},
"BTest": {
"1": "1",
"2": "2"
},
"Value4": {
"value4value": "value4value"
},
"ATest": {
"1": "1",
"2": "2"
},
"Value5": {
"value5value": "value5value",
"value6value": "value6value"
},
"TestA": {
"1": "1",
"2": "2"
}}
let newObj={};
Object.keys(obj).forEach(k=>{
if(k.startsWith('Value')){
newObj[k]=obj[k];
}
})
console.log(newObj)

If you do not want to use startwith etc and want to use full names how about this, You create an array with the names that you want to remove and than simply check add keys that are not in that array to new object. Something like this
const removeableItems = ["TestA", "BTest", "ATest"]
let newObj = {}
for (var key in obj) {
if (obj.hasOwnProperty(key) && !removeableItems.includes(key)) {
newObj[key] = obj[key];
}
}
Here is a blitz showing this.

You can use Object.assign() and Spread syntax combined with Object.keys(), Array.prototype.filter(), Array.prototype.map() and String.prototype.startsWith():
const Obj = {"Value1": {"value1value": "1"},"Value2": {"value2value": "2"},"Value3": {"value3value": "3"},"BTest": {"1": "1","2": "2"},"Value4": {"value4value": "value4value"},"ATest": {"1": "1","2": "2"},"Value5": {"value5value": "value5value","value6value": "value6value"},"TestA": {"1": "1","2": "2"}};
const result = Object.assign(
{},
...Object.keys(Obj)
.filter(k => k.startsWith('Value'))
.map(k => ({ [k]: Obj[k] }))
);
console.log(result);

Related

Compare object properties by keys in javascript

I'm trying to make a comparison of the object properties by key.
There are some sample data:
const data = [{
"name": "John",
"value": "30"
}, {
"name": "Cindy",
"value": "50"
}, {
"name": "Mathew",
"value": "80"
}, {
"name": "Mike",
"value": "35"
}];
so I would like to compare property values(value) of John and Mike names(key). If value of Mike is different than John than mutate value of Mike with value of John.
There is some algorithm
data.map(obj => {
for (const key in obj) {
if (obj.hasOwnProperty(key)) {
let johnValue;
let mikeValue;
if(obj[key] == 'John') {
johnValue = Number(obj.value)
}
else if(obj[key] == 'Mike') {
mikeValue = Number(obj.value)
}
if(johnValue != mikeValue) {
newData = {
...data,
"Mike": johnValue
}
}
}
}
})
after whose execution I expected data like
const data = [{
"name": "John",
"value": "30"
}, {
"name": "Cindy",
"value": "50"
}, {
"name": "Mathew",
"value": "80"
}, {
"name": "Mike",
"value": "30"
}];
Is there a way to write it better using some of the ES6 features?
Fiddle
Yes, you can do it a bit shorter
const MikeRecordInd = data.findIndex(v => v.name === 'Mike')
const JohnRecord = data.find(v => v.name === 'John')
if (data[MikeRecordInd].value !== JohnRecord.value) {
newData = [...data]
newData[MikeRecordInd] = { name: 'Mike', value: JohnRecord.value }
}

javascript cannot map array of objects with nested values

Trying to map array of objects with values nested in child objects structure like:
const objs = [{
"B": {
"value": 1,
},
"D": {
"value": "45"
},
"E": {
"value": "234"
},
"A": {
"value": "543"
},
"C": {
"value": "250"
}
},...]
to the structure like:
[
{ name: 'B', value: 1 },
{ name: 'D', value: '45' },
{ name: 'E', value: '234' },
{ name: 'A', value: '543' },
{ name: 'C', value: '250' }
]
and the result of the mapping is undefined
const mapped = objs.map((key, index) => {
Object.keys(key).map(el => ({
name: el
}))
})
Example: Stackblitz
You are missing return statement and value property definition.
Besides you may want to use flatMap instead of map in order to avoid a nested array in the result:
const objs = [{
"B": {
"value": 1,
},
"D": {
"value": "45"
},
"E": {
"value": "234"
},
"A": {
"value": "543"
},
"C": {
"value": "250"
}
}]
const mapped = objs.flatMap((key, index) => {
return Object.keys(key).map(el => ({
name: el,
value: key[el].value
}))
})
console.log(mapped)
You should operate on objs[0], not objs, because it is an array of one object, not array of objects.
let array = []
for(let object in objs[0]){
array.push({
"name": object,
"value": objs[0][object].value
})
}
return is missing in Object.keys. As well instead of Object.keys use Object.entries to get key and value.
const objs = [{
"B": {
"value": 1,
},
"D": {
"value": "45"
},
"E": {
"value": "234"
},
"A": {
"value": "543"
},
"C": {
"value": "250"
}
}];
const mapped = objs.map((key, _) => {
return Object.entries((key)).map(([name, {
value
}]) => ({
name,
value
}))
}).flat();
console.log(mapped);

How to make a JSON object out of a dictionary?

I'me new to JavaScript. In the browser I receive a long dictionary like this:
{"cat": "4" , "dog": "5", "fish": "9" }
I'm wondering what is the most efficient way to convert it to a JSON object like:
[
{
"name": "cat",
"value": "4"
},
{
"name": "dog",
"value": "5"
},
{
"name": "fish",
"value": "9"
}
]
You can Loop through it and push each key-value-pair to an Array.
var tValue = {"cat": "4" , "dog": "5", "fish": "9" };
var tList = [];
for(var tKey in tValue) tList.push({name: tKey, value: tValue[tKey]});
console.log(tList);
You can just loop over the dictionary object keys using Object.keys() method, and use .map() method to transform each iterated key/value pair to the appropriate object:
var results = Object.keys(obj).map(function(k) {
return {
name: k,
value: obj[k]
};
});
Demo:
var obj = {
"cat": "4",
"dog": "5",
"fish": "9"
};
var results = Object.keys(obj).map(function(k) {
return {
name: k,
value: obj[k]
};
});
console.log(results);
You can use the function Object.entries to get every key-value pairs and with the function map build the desired output.
let obj = {"cat": "4" , "dog": "5", "fish": "9" },
result = Object.entries(obj).map(([name, value]) => ({name, value}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
You can do this by this way :
Call a for in loop and read your first object
Push the name and the value in your new object one by one..
Sample code :
var a = {"cat": "4" , "dog": "5", "fish": "9" };
var newJSON = [] ;
console.log(a);
for ( key in a ) {
newJSON.push({name : key, value : a[key]});
}
console.log(newJSON);
You can have this kind of formatted object
{
animals : [
{"name":"cat", "value": 4},
{"name":"dog", "value": 5},
{"name":"fish", "value": 9}
]
}
or like this
[
{"name":"cat", "value": 4},
{"name":"dog", "value": 5},
{"name":"fish", "value": 9}
]

Change representation of JSON object to explicit key/value format

I have the following JSON:
{
"temperature": "22.2",
"power": "6",
"current": "156"
}
and I need to convert it to this explicit structure:
{
"key": "temperature",
"value": "22.2"
},
{
"key": "power",
"value": "6"
},
{
"key": "current",
"value": "156"
}
Is there an elegant, simple and quick way to do this?
Best, thx
var newStructure = Object.keys(obj).map(function(key){
return {'key':key, 'value':obj[key]}
})
Example
var obj = {
"temperature": "22.2",
"power": "6",
"current": "156"
}
var arr = Object.keys(obj).map(function(key){return {'key':key,'value':obj[key]}})
console.log(arr)
Object.hashToKeyValuePairs = function (hash) {
var ret = [];
for (var i in hash)
ret.push({ key: i, value: hash[i]});
return ret;
};
// example
document.body.innerHTML = JSON.stringify(
Object.hashToKeyValuePairs({ a: 1, b: 2, c: 3 })
);

how to parse json string contains circular reference in javascript?

I have the following json string in javascript. This string contains a circular references. I want to parse this string in such a way that the reference will be replaced by its actual object. I use Json.Parse but it creates the json object with references. Is there any way by whihc i can achieve this ?
{
"$id": "1",
"$values": [
{
"$id": "2",
"Event": {
"$id": "3",
"Invitaions": {
"$id": "4",
"$values": [
{
"$ref": "2"
},
{
"$id": "5",
"Event": {
"$ref": "3"
},
"Id": 2,
"Name": "test2",
"Date": "24",
"EventId": 1
}
]
},
"Id": 1,
"Name": "marriage",
"Address": "abcd"
},
"Id": 1,
"Name": "test1",
"Date": "23",
"EventId": 1
},
{
"$ref": "5"
},
{
"$id": "6",
"Event": {
"$id": "7",
"Invitaions": {
"$id": "8",
"$values": [
{
"$ref": "6"
}
]
},
"Id": 2,
"Name": "birthday",
"Address": "abcd"
},
"Id": 3,
"Name": "test3",
"Date": "25",
"EventId": 2
}
]
}
This should do it:
function resolveReferences(json) {
if (typeof json === 'string')
json = JSON.parse(json);
var byid = {}, // all objects by id
refs = []; // references to objects that could not be resolved
json = (function recurse(obj, prop, parent) {
if (typeof obj !== 'object' || !obj) // a primitive value
return obj;
if ("$ref" in obj) { // a reference
var ref = obj.$ref;
if (ref in byid)
return byid[ref];
// else we have to make it lazy:
refs.push([parent, prop, ref]);
return;
} else if ("$id" in obj) {
var id = obj.$id;
delete obj.$id;
if ("$values" in obj) // an array
obj = obj.$values.map(recurse);
else // a plain object
for (var prop in obj)
obj[prop] = recurse(obj[prop], prop, obj)
byid[id] = obj;
}
return obj;
})(json); // run it!
for (var i=0; i<refs.length; i++) { // resolve previously unknown references
var ref = refs[i];
ref[0][ref[1]] = byid[refs[2]];
// Notice that this throws if you put in a reference at top-level
}
return json;
}
You should check out Douglas Crockfords JSON-js repo on github: https://github.com/douglascrockford/JSON-js
There's a cycle.js in there that helps you do exactly what you're looking for.
Look at my post here, I've found some bugs in the code above and there wasn't arrays support, check out my improved version: Resolve circular references from JSON object

Categories