logo
down
shadow

Swift - Merging 2 arrays of objects with a key


Swift - Merging 2 arrays of objects with a key

By : user3099393
Date : January 11 2021, 03:32 PM
fixed the issue. Will look into that further I'm new to Swift programming and been working on an app fir a couple of weeks now, and I'm stuck at a crucial moment in the development. , I figure it out!
code :
        for mergedI in mergeInformationList {
            for mergedD in mergeDataList {
                if mergedI.id == mergedD.id {
                    self.mergedList.append(MergedViewModel(data: mergedD, information: mergedI))

                }
            }
        }


Share : facebook icon twitter icon
Merging two arrays of objects

Merging two arrays of objects


By : sunshine21
Date : March 29 2020, 07:55 AM
hope this fix your issue You can achieve this using jQuery extend if that's an option.
code :
var extendedArray = $.extend({}, arr1, arr2);
$.extend(arr1, arr2);
JavaScript Merging 3 Arrays of Objects into 1 Array of Objects by ID and Name

JavaScript Merging 3 Arrays of Objects into 1 Array of Objects by ID and Name


By : Nelson Rodriguez Ros
Date : March 29 2020, 07:55 AM
like below fixes the issue There are a number of ways you could do this. Here is a very old-school but fast way to do it. It involves two steps:
Take all the arrays and merge them into an object using the specified key ('Client ID' in this example). Take that merged object and convert it back to an array.
code :
var arr1 = [
{"Client ID":"1", "Client Name":"ABC", D1:"some data", D2:"more data"},
{"Client ID":"2", "Client Name":"DEF", D1:"some data", D2:"more data"},
{"Client ID":"3", "Client Name":"GHI", D1:"some data", D2:"more data"}
];

var arr2 = [
{"Client ID":"1", "Client Name":"ABC", D3:"and more data", D4:"more more data"},
{"Client ID":"2", "Client Name":"DEF", D3:"and more data", D4:"more more data"},
{"Client ID":"3", "Client Name":"GHI", D3:"and more data", D4:"more more data"}
];

var arr3 = [
{"Client ID":"1", "Client Name":"ABC", D5:"other data", D6:"extra Data"},
{"Client ID":"2", "Client Name":"DEF", D5:"other data", D6:"extra Data"},
{"Client ID":"3", "Client Name":"GHI", D5:"other data", D6:"extra Data"}
];

console.log( mergeArrays( 'Client ID', [ arr1, arr2, arr3 ] ) );

function mergeArrays( key, arrays ) {
    // First merge the arrays into an object
    // indexed by the specified key
    var merged = {};
    arrays.forEach( function( array ) {
        array.forEach( function( item ) {
            var id = item[key];
            var target = merged[id];
            if( ! target ) target = merged[id] = {};
            for( var name in item ) {
                if( item.hasOwnProperty(name) ) {
                    target[name] = item[name];
                }
            }
        });
    });
    // Now convert the merged object back to an array
    var result = [];
    for( var id in merged ) {
        if( merged.hasOwnProperty(id) ) {
            result.push( merged[id] );
        }
    }
    return result;
}
Transform multiple arrays of objects into a single array while merging the objects on common key

Transform multiple arrays of objects into a single array while merging the objects on common key


By : Caio Cesar
Date : March 29 2020, 07:55 AM
will help you Try following
Create an object with date as key and corresponding resulting object as value. And using Object.values get the final result To build the object, use Array.reduce on outer array and for each value of inner array, check whether the entry for date exists or not in object. If it exists update it else create a new entry in object. For each object in inner array, sum the values of all keys except date and set it in object corresponding to the customer name key.
code :
const myArray = [{values: [{ date: "2018-11-02", "value1": 3, "value2": 5 },{ date: "2018-11-01", "value1": 8, "value2": 9 },{ date: "2018-10-31", "value1": 4, "value2": 10 },],customer: "Customer One"},{values: [{ date: "2018-11-02", "value1": 3 },{ date: "2018-11-01", "value1": 5 },{ date: "2018-10-31", "value1": 8 },],customer: "Customer Two"}];

let result = Object.values(myArray.reduce((a,c) => {
  c.values.forEach(({date, ...rest}) => {
    a[date] = a[date] || {date};
    a[date][c.customer] = Object.values(rest).reduce((d,e) => d + e);
  });
  return a;
}, {}));
console.log(result);
Merging 2 arrays of objects to create a Map of Objects

Merging 2 arrays of objects to create a Map of Objects


By : ben leppard
Date : March 29 2020, 07:55 AM
help you fix your problem You could iterate the outer object's keys and then the inner arrays. If an result object does not exist, create one with the wanted keys and zero values.
Merging two arrays of structures using iOS swift

Merging two arrays of structures using iOS swift


By : D shokry
Date : March 29 2020, 07:55 AM
This might help you How can I merge two (first and second) arrays of structures based on a key in structure (name). While merging I need to replace the existing element of first array with second array element, if any value changed in that element.
code :
import Foundation

struct Example: Codable {
    var name: String
    var dob: String
    var address: String
}

var first: [Example] = []
var second: [Example] = []

first.append(Example(name: "Arun", dob: "01-01-1994", address: "Tirupati"))
first.append(Example(name: "Balaji", dob: "01-01-1994", address: "Tirupati"))
first.append(Example(name: "Prasanth", dob: "01-01-1994", address: "Tirupati"))

second.append(Example(name: "Arun", dob: "01-01-1994", address: "Kadapa"))
second.append(Example(name: "Balaji", dob: "01-01-1994", address: "Tirupati"))
second.append(Example(name: "Prasanth", dob: "01-01-1994", address: "Tirupati"))
second.append(Example(name: "Harsha", dob: "01-01-1994", address: "Tirupati"))

first = second + first.filter { element in
    return !second.contains { $0.name == element.name }
}
Related Posts Related Posts :
  • Add 'PageSetupAccessory' to PrintPanel for PDFDocument
  • I want to display two nodes overlapping each other with ARKit
  • Run Kitura Docker Image causes libmysqlclient.so.18 Error
  • How would you switch through kCL error in Swift?
  • How should I use this Github project properly?
  • How does my teacher know how many parameters to put in her closures and how does she know what type Swift will infer?
  • Custom Index for Linked List in Swift
  • Swift WKWebView continuous spell checking
  • Change frame of Live View in Swift playgrounds
  • Swift: Maintaining atomicity in a block-based execution using weak self
  • Why memory address is not changed for different instances of struct?
  • Filling a List in SwiftUI with CoreData
  • Kotlin Property Initialization (Like swift using closures)
  • Call a function from a separate class not working
  • Explanation of zip, reduce and combine in Swift
  • How to add a delay between loops when playing a tone in AVAudioPlayer?
  • How to add storyboard canvas orientation in git ignore in Xcode
  • How to execute different implementation of a method of a generic struct based on the generic type?
  • How to handle Errors on never ending chain with materialize?
  • RxSwift convert Observable<String> into String
  • Alamofire sending a request to an API 'NSInvalidArgumentException'
  • SwiftUI Conditional List - Unable to infer complex closure return type
  • Result values in '? :' expression have mismatching types 'String.SubSequence' (aka 'Substring') and 'String'
  • SwiftUI - Align contents of Button to the left
  • Swift handle did select on multiple annotations on same location
  • How to use NSPredicate for whether a List of Int contains a Int number?
  • SetNeedsDisplay having no effect
  • Can't initialize class with "if"
  • SKPaymentQueue.default().add(payment) ignored
  • How to share UIImage to Camera Roll using UIActivityViewController
  • Play Sound From String Arrays Swift
  • Runtime error using Combine: dyld: Symbol not found: _$s7Combine9PublishedV9PublisherCyx_GAadAMc
  • addPeriodicTimeObserver generate a escaping closure error
  • Since iOS 13 Beta 3, my app only displays a black window
  • showing uiview controller as a pop up
  • SwiftUI Beta 3 Black Screen
  • What is Content in SwiftUI?
  • How do I access the underlying key of a SymmetricKey in CryptoKit?
  • How to get dynamic Text height for a ScrollView with SwiftUI
  • SwiftUI: NavigationButton initializer gives error
  • How to limit character for username in Swift
  • How do I use UserDefaults with SwiftUI?
  • I'm an absolute beginner in swift. I don't what's wrong with the output of my code, This is based on mutating methods
  • How to reload data in UITableView when popping view controller
  • Cannot hook into another RxSwift stream based on a check
  • SwiftUI Change View with Button
  • SwiftUI: How to draw filled and stroked shape?
  • How to access inner object's properties from superclass without boilerplate
  • SwiftUI Table Custom Swipe?
  • Unwrapping optional inside map closure in Swift
  • What is the best way to wrap `purchaserInfo` for easy comparisons throughout your code using RevenueCat
  • How to shuffle multidimensional array?
  • Can you use a Publisher directly as an @ObjectBinding property in SwiftUI?
  • Changing certain words' colour in SCNText
  • Limit frequency with which firestore retrieves data
  • SwiftUI - Half modal?
  • Call a function multiple times and get a list of results in swift?
  • Open multiple preview same time in SwiftUI
  • What is simdTransform in SceneKit and ARKit?
  • How can I fill only part of the custom UIView rectangle?
  • shadow
    Privacy Policy - Terms - Contact Us © festivalmusicasacra.org