Reputation: 799
I have a database function that returns some rows from a sqlite database then stores that in state
rows = await ReturnSelectedSymbolsDB()
this.setState({ symbols: rows })
The array looks something like this
symbols: [{key: "0", symbol:"name1", active: false},{key:"1", symbol:"name2",active: false}]
I have another database function which returns some rows and I wish to add them to symbol
so it would look like this.
symbols: [{key: "0", symbol:"name1", active: false, newKey: newValue},{key:"1", symbol:"name2",active: false, newKey, newValue2}]
The second function will return multiple rows from the database which will be easy to match up with symbols
as symbols:symbol will match otherFunction:symbol.
Normally you would just write this like a regular SQL query with a inner join joining the 2 tables together and then just putting the resulting rows in a state variable but I cannot in this case and must build the state variable piece by piece.
Can this be done is regular javascript?
EDIT:
Probably wasnt clear but newKey
can have different values depending on what the name of the symbol
is
Upvotes: 0
Views: 3796
Reputation: 4425
You have to insert your new value into your first function array, there are couples of way can insert object in array either use for loop or array manipulation functions.
var arrOfObj = [{
key: "0",
symbol:"name1",
active: false
}, {
key: "1",
symbol:"name1",
active: false
}, {
key: "2",
symbol:"name1",
active: false
}];
var result = arrOfObj.map(function(o) {
o.newKey = newValue;
return o;
})
console.log(result)
Note: I would prefer to go with inner join with two tables to return combine array that not require any array manipulation.
Upvotes: 1
Reputation: 4961
Try this,
let symbols = [
{ key: "0", symbol: "name1", active: false },
{ key: "1", symbol: "name2", active: false }
];
let newSymbols = [
{ key: "1", symbol: "name1", newKey: "fdds" },
{ key: "0", symbol: "name2", newKey: "sadav" }
];
mergeArray = (arrayOld, arrayNew) => {
let output = arrayOld.filter(item => {
let find = findMatchingItem(arrayNew, item.key);
item["newKey"] = find.newKey;
return item;
});
return output;
};
findMatchingItem = (array, matchingItemKey) => {
let output = null;
array.map(item => {
if (item.key == matchingItemKey) {
output = item;
}
});
return output;
};
let newArray = mergeArray(symbols, newSymbols);
console.log(newArray);
I have matched objects using "key"
if you want from "symbol"
just change "key"
to "symbol"
Upvotes: 0
Reputation: 3384
You can create a new util function where you can add new key to all object inside the array.
addKey(symbol) {
let newArray=[...symbol];
return newArray.map((ele, i) => {
return {...ele, newKey: newValue};
})
}
Happy Coding :)
Upvotes: 2
Reputation: 372
You could do something like this if you know the key value corresponding to a given symbol:
for (let i = 0; i < symbols.length; i++){
symbols[i].newKey = "anyValue"
}
Upvotes: 0